如何用原型链实现继承
function Animal(legs) {
this.legs = legs;
}
Animal.prototype.kind = "动物";
// 现在想要做的是,如何继承Animal的legs,又继承Animal的prototype上的内容
function Duck(name) {
this.name = name;
Animal.call(this, 4); // 继承了来自Animal的legs,这一步的实现逻辑是怎样的
}
// 给Duck添加共有属性
Duck.prototype.say = function () {
alert("嘎嘎嘎");
};
Duck.prototype.eyes = 2;
// 将Duck的prototype属性的原型设置为Animal.prototype
// 这样Duck就能够使用Animal中的方法了
Object.setPrototypeOf(Duck.prototype, Animal.prototype);
const smallDuck = new Duck("小黄");
console.dir(smallDuck); // 查看有没有来自Animal的legs,查看Duck的prototype属性的原型是否为Animal.prototype
下面这一步的实现逻辑是怎样的
function Duck(name) {
this.name = name;
Animal.call(this, 4); // 继承了来自Animal的legs,这一步的实现逻辑是怎样的
}
解答:关键要理解new关键字是怎么运行的
const smallDuck = new Duck('小黄');
1.新的对象被创建
2.将对象绑定prototype
3.新的对象被分配给this
4.执行函数体 Duck('小黄')
- this.name = name
就增加了name属性'小黄',往创建的空对象中放
这时对象变成了{ name:'小黄'}
- 然后Animal.call(this,4) 执行对应函数
function(4) {
this.legs = 4;
}()
这时对象变成了{name:'小黄',legs:4}
5.返回this
如何用class实现继承
class Animal {
variety ='碳基生物'
constructor(legs) {
this.legs = legs
}
}
class Duck extends Animal{
constructor(name) {
// super是调用父类的方法,要放在上面
super(4);// 用相应参数执行父类的constructor
this.name = name;
}
say() {
alert('嘎嘎嘎')
console.log(this.name,this.legs)
}
}
const smallDuck = new Duck('小黄')
console.dir(smallDuck)