继承
就是继承原型 有很多种方法 但可以分为两类
1.继承原型及属性
2.共用原型复制属性
1.继承原型及属性
//父类
//定义在原型上的init方法
Person.prototype.init = function() {
console.log(this.name + "在读书")
}
//定义在原型上的属性方法
Person.prototype.abc = 3
function Person(name, age) {
this.name = name;
this.age = age
}
// 子类
function Student(name, age) {
this.uber(name, age)
}
//继承方法
function inherit(father, son) {
// 复制一份父级的原型
son.prototype = Object.create(father.prototype)
//由于复制了所以constructor的指向发生了改变 需要改回来
son.prototype.constructor = son;
//这里用一个属性来得到父级的构造方法(记录)
son.prototype.uber = father;
}
inherit(Person, Student)
Student.prototype.xage = function() {
console.log(`${this.name}今年${this.age}`)
}
var hong = new Student('小红', 21);
当我们输出hong的时候返回的是
这种类型的继承是全部属性都有 互不影响
2.共用原型复制属性
//原始继承
function Father() {
this.name = '小鱼'
this.car = {
car1: "兰博",
car2: "盛德"
}
}
function Son() {
this.age = 17
}
Father.prototype.init = function() {
console.log(this.name + "今年" + this.age)
}
Father.prototype.abc = "123"
// 用一个对象来作为儿子的原型来使用
var father = new Father()
Son.prototype = father
var son = new Son()
当我们输出son 的时候返回的是
当我们去改子类的原型
son.car.car1 = "古耐"