shfshanyue / Daily-Question

互联网大厂内推及大厂面经整理,并且每天一道面试题推送。每天五分钟,半年大厂中
https://q.shanyue.tech
4.95k stars 510 forks source link

【Q561】实现一个 inherits 函数进行继承 #576

Open shfshanyue opened 3 years ago

shfshanyue commented 3 years ago

使用方法如 inherits(Dog, Animal);DogAnimal 进行了继承

mrrs878 commented 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']
haotie1990 commented 3 years ago
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;
}
shfshanyue commented 3 years ago

TODO