Open shfshanyue opened 3 years ago
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']
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;
}
TODO
使用方法如
inherits(Dog, Animal);
,Dog
对Animal
进行了继承