请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

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

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);

经测试可用

正在回答 回答被采纳积分+3

2回答

keviny79 2022-03-27 22:08:35

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

0 回复 有任何疑惑可以回复我~
keviny79 2021-08-19 13:11:35

是的 正确,但在大中项目中,还是建议用自己手写的源码优化中的方式来封装,原因有两个  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 回复 有任何疑惑可以回复我~
问题已解决,确定采纳
还有疑问,暂不采纳
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号