实现一个 inherits 函数进行继承
更多描述 使用方法如
inherits(Dog, Animal);
,Dog
对Animal
进行了继承
Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 576 (opens in a new tab)
Author 回答者: mrrs878 (opens in a new tab)
function inherits(SuperType, SubType) {
const pro = Object.create(SuperType.prototype);
pro.constructor = SubType;
SubType.prototype = pro;
}
function SuperType(friends) {
this.friends = friends;
}
SuperType.prototype.getFriends = function () {
console.log(this.friends);
};
function SubType(name, friends) {
this.name = name;
SuperType.call(this, friends);
}
inherits(SuperType, SubType);
SubType.prototype.getName = function () {
console.log(this.name);
};
const tom = new SubType("tom", ["jerry"]);
tom.getName();
// 'tom'
tom.getFriends();
// ['jerry']
tom.friends.push("jack");
tom.getFriends();
// ['jerry', 'jack']
Author 回答者: haotie1990 (opens in a new tab)
function objectCreate(prototype) {
const F = function () {};
F.prototype = prototype || Object.prototype;
return new F();
}
function inheritPrototype(child, parent) {
child.prototype = objectCreate(parent.prototype);
child.prototype.constructor = child;
}
Author 回答者: shfshanyue (opens in a new tab)
TODO