在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML/ 關(guān)于js實(shí)現(xiàn)繼承的方法可否利用 Object.setPrototypeOf()

關(guān)于js實(shí)現(xiàn)繼承的方法可否利用 Object.setPrototypeOf()來實(shí)現(xiàn)繼承父類原型上的方法?

1.看了高程上的寄生組合繼承了解到繼承父類原型上的方法主要是這段代碼實(shí)現(xiàn)的

       let prototype = Object.create(Person.prototype);
       prototype.constructor = Son;
       Son.prototype = prototype;

我試了試如果用

     Object.setPrototypeOf(Son.prototype,Person.prototype)

同樣可以實(shí)現(xiàn)繼承父組件
用第二種有什么缺點(diǎn)嗎?
這里有個(gè)jsfiddle的例子可以查看傳送門

回答
編輯回答
墨染殤

可以,這是nodejs的源碼,事實(shí)上這種原生方法更快。

function inherits(ctor, superCtor) {

  if (ctor === undefined || ctor === null)
    throw new TypeError('The constructor to "inherits" must not be ' +
                        'null or undefined');

  if (superCtor === undefined || superCtor === null)
    throw new TypeError('The super constructor to "inherits" must not ' +
                        'be null or undefined');

  if (superCtor.prototype === undefined) {
    throw new TypeError('The super constructor to "inherits" must ' +
                        'have a prototype');
  }

  ctor.super_ = superCtor;
  Object.setPrototypeOf(ctor.prototype, superCtor.prototype);
}

nodejs inherits

2018年7月10日 23:32
編輯回答
敢試

沒問題~ 只不過setPrototypeOf是 ES6 語法。

2017年2月8日 18:57