使用Object.create()也可以封装

来源:5-11 【TS继承准备】寄生组合继承实现方式【最佳继承模式】-3

crazyones110

2021-08-19

function Son(name, gender, hobby) {
  Father.call(this, name, gender);
  this.hobby = hobby;
}
function Father(name, gender) {
  this.name = name;
  this.gender = gender;
}

Father.prototype.walk = () => console.log("I can walk");
function extends2_(son, father) {
  const obj = Object.create(father.prototype, {
    constructor: {
      value: son
    }
  });
  son.prototype = obj;
}
extends2_(Son, Father);
const son = new Son("zhangsan", "male", "basketball");
console.log("son", son);

经测试可用

写回答

2回答

keviny79

2022-03-27

修正一个书写错误:参见截图,看本节的同学看过来。//img.mukewang.com/szimg/62406fb8082a611311870736.jpg

0
0

keviny79

2021-08-19

是的 正确,但在大中项目中,还是建议用自己手写的源码优化中的方式来封装,原因有两个  1.可以在日后 Middle 构造函数增加内容,扩展更方便    2.效率要高于Objec.create底层调用方式  当然主要原因还是第1点

  return function (Son, Parent) {

    MyextendStatics(Son, Parent)

    function Middle () {

      this.constructor = Son;

    }

    if (Parent) {//如果不为空 如果父类存在

      Middle.prototype = Parent.prototype;

      Son.prototype = new Middle()

    } else {// 如果父类不存在

      Son.prototype = Object.create(null)

    }

    console.log("Object.create(null):", Object.create(null));

  }

}())


0
2
keviny79
回复
weixin_精慕门4453311
谢谢同学!
2022-03-27
共2条回复

晋级TypeScript高手,成为抢手的前端开发人才

轻松驾驭 TypeScript 高级用法, 突破前端成长瓶颈

871 学习 · 425 问题

查看课程