js组合寄生分析

54 阅读1分钟

js组合寄生分析

  1. 了解prototype
  2. 了解Object.create
  3. 组合继承实现
  1. 了解prototype
  • ①__proto__和constructor属性是对象所独有的;② prototype属性是函数所独有的。
  • 每个函数在创建的时候,JS会同时创建一个该函数对应的prototype对象,因此函数.prototype.constructor===该函数本身
  • prototype作用: 创建对象共享成员,相当于static

2.了解Object.create

  • 相当于只保留了原型对象的空函数
function createObj(o) {
    function F() {}
    F.prototype = o;
    return new F();
} 

3、组合继承实现

  • 创建空函数 继承父原型
  • 将具有父原型的对象与空函数绑定
/* 组合寄生 */
function inherit(son, father) {
// 步骤一
let tmpObj = Object.create(father.prototype); //不发生第二次继承
console.log(tmpObj);

// 第二步和第三部就是实现绑定只有原型的空对象和子类绑定

// 步骤二,设置原型对象的consturctor指针
tmpObj.constructor = son;
// 步骤三,设置子函数的prototype
son.prototype = tmpObj;
}

测试代码

function SuperType(name) {
  this.name = name;
  this.colors = ['red', 'green', 'black'];
}
SuperType.prototype.sayName = function () {
  return this.name;
};
function SubType(name, age) {
  SuperType.call(this, name); //继承一次
  this.age = age;
}

/* 组合寄生 */
function inherit(son, father) {
  // 步骤一
  let tmpObj = Object.create(father.prototype); //不发生第二次继承
  console.log(tmpObj);

  // 步骤二
  tmpObj.constructor = son;

  // 步骤三
  son.prototype = tmpObj;
}
inherit(SubType, SuperType);

SubType.prototype.sayAge = function () {
  return this.age;
};

let superType02 = new SuperType('测试一号');
let subType02 = new SubType('测试一号', 18);

console.log(superType02);
console.log(subType02);