wang1dot0 / personal-note

记录工作中遇到的个人觉得比较有意思的小问题
https://github.com/wang1dot0/personal-note
0 stars 0 forks source link

[js] 继承 #35

Open wang1dot0 opened 4 years ago

wang1dot0 commented 4 years ago

ES5经典模式有6种 一 原型链继承

function Parent(name, age) {
  this.pName = name;
  this.pAge = age;
}
Parent.prototype.getName = function() {
  return this.pName;
}
function Child(name, age) {
  this.cName = name;
  this.cAge = age;
}
Child.prototype = new Parent('John', 55);
Child.prototype.constructor  = Child;

二 构造函数继承

function Child(name, age) {
  Parent.call(this, name, age);
}

三 组合继承

function Child(name, age) {
  Parent.call(this, name, age);
}
Child.prototype = new Parent();

四 原型继承

var object = new Parent('John', 35);
function Child(object) {
  function F() {};
  F.prototype = object;
  return new F();
}
// 是Object.create()实现的原理

五 寄生式继承

function content (obj) {
  function F() {}
  F.prototype = obj;
  return new F();
}
function Child(object) {
  var obj = content(object);
  obj.sayName = function() { return this.name };
  return obj;
}

六 寄生组合式继承

function content (obj) {
  function F() {}
  F.prototype = obj;
  return new F();
}
var proto = content(Parent.prototype)
function Child() {
  Parent.call(this);
}
Child.prototype = proto;