没有Cat.prototype = Object.create(Animal.prototype)这一句,竟然也能得到同样的结果?
来源:4-6 JS面向对象深层填坑—ES5
诺丁山丶
2018-08-16
(function () {
"use strict";
var Animal = function (name, age) {
this.name = name;
this.age = age;
};
Animal.prototype.say = function () {
console.log(this.name + ' ' + this.age);
};
var cat = new Animal('猫咪', 3);
cat.say();
// Animal.prototype.say.apply(cat);
// var params = {
// name: '猫咪2号',
// age: '6'
// };
//
// cat.say.call(params);
// 寄生组合继承
var Cat = function (name, age) {
Animal.apply(this, arguments);
};
Cat.prototype.say = function () {
var p = {
name: '父猫咪',
age: 10
};
Animal.prototype.say.apply(p);
console.log('这是子类的名字' + this.name + this.age);
};
var cat1 = new Cat('子猫咪', 7);
cat1.say();
})();得到的结果:
猫咪 3
父猫咪 10
这是子类的名字子猫咪7
请问是为什么?
写回答
2回答
-
傅猿猿
2018-08-17
因为在调用它的时候已经绑定在原型链上了啊,这个不要深扣,es5这里本来就是反人类的设计,理论上应该想办法去忘掉不要受影响才对,大概了解下就好,es6才是正常人的写法
10 -
诺丁山丶
提问者
2018-08-17
哈哈,明白了,谢谢老师
00
相似问题