假设我有一个具有speak功能的动物对象:functionspeak(){console.log(this.sound)}letanimal={speak}我有一只狗,它会发出声音:letdog={sound:"Woof!"}如果我想让dog从animal继承speak我可以使用Object.assign或对象.setPrototypeOf。它们似乎产生相同的结果:letluke=Object.assign(dog,animal)luke.speak()//Woof!letbruno=Object.setPrototypeOf(dog,animal)bruno.speak()//Woo
将以下代码发布到BabelREPLclassTest{}classTest2extendsTest{}你得到了这个inherits函数function_inherits(subClass,superClass){if(typeofsuperClass!=="function"&&superClass!==null){thrownewTypeError("Superexpressionmusteitherbenullorafunction,not"+typeofsuperClass);}subClass.prototype=Object.create(superClass&&superC
MDN暗示使用.setPrototypeOf()会对代码的future性能产生不良影响。我还阅读了一些关于为什么更改对象的[[Prototype]]会降低性能的问题。但是没有一个答案真正解释了后台发生的事情。所以我想知道这是否也适用于新对象。我特别喜欢做这样的事情:varMyPrototype={method1:function(){...},method2:function(){...},...};varnewObject=Object.setPrototypeOf({property:1,property2:'text'},MyPrototype);不幸的是,您不能使用Object
显然使用__proto__属性仍然是操作原型(prototype)链的主要方式,尽管这不符合标准并且IE不支持它。虽然您也可以通过使用new构造函数构造继承,但与__proto__属性或符合标准的Object.getPrototypeOf函数相比,这似乎是一个不必要的复杂化.编辑:如答案中所述,此方法现在确实存在(ES6标准)。但是请注意性能警告:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/setPrototypeOf 最佳答案
MDN有一个关于修改代码原型(prototype)的巨大警告:Changingthe[[Prototype]]ofanobjectis,bythenatureofhowmodernJavaScriptenginesoptimizepropertyaccesses,averyslowoperation,ineverybrowserandJavaScriptengine.Theeffectsonperformanceofalteringinheritancearesubtleandfar-flung,andarenotlimitedtosimplythetimespentintheObje