1. Object.setPrototypeOf
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/setPrototypeOf
Object.setPrototypeOf(obj, proto)
,用来将obj.__proto__
设置为proto
。
注:
该方法相当于修改一个对象的内置属性[[Prototype]],是一个非常慢的操作,
因为现代浏览器或JavaScript引擎都对属性访问进行过优化。
修改内置属性,是一件影响范围很大的事情,并不仅仅意味着赋值obj.__proto__ = ...
,
而是可能会涉及所有用过该属性的代码,以及可能访问该属性的对象。
考虑到性能,应该尽可能避免使用该方法,
而是使用Object.create
方法,根据给定原型创建一个新对象。
Warning: Changing the [[Prototype]]
of an object is, by the nature of how modern JavaScript engines optimize property accesses, a very slow operation, in every browser and JavaScript engine. The effects on performance of altering inheritance are subtle and far-flung, and are not limited to simply the time spent in obj.proto = ...
statement, but may extend to any code that has access to any object whose [[Prototype]]
has been altered. If you care about performance you should avoid setting the [[Prototype]]
of an object. Instead, create a new object with the desired [[Prototype]]
using Object.create()
.
2. Object.getPrototypeOf
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf
Object.getPrototypeOf(obj)
,返回obj.__proto__
。