美文网首页JavaScript
[JavaScript] Object.setPrototype

[JavaScript] Object.setPrototype

作者: 何幻 | 来源:发表于2016-09-18 16:28 被阅读94次

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__

相关文章

网友评论

    本文标题:[JavaScript] Object.setPrototype

    本文链接:https://www.haomeiwen.com/subject/ntqgettx.html