我知道两种继承函数构造函数的方法。
选项 1 Object.create
function x(x, y) {
this.x = x;
this.y = y;
}
x.prototype.XDD = function() {};
function y(c, r) {
x.call(this, 1, 2);
this.r = r;
this.c = c;
}
y.prototype = Object.create(x.prototype);
y.prototype.YDD = function() {};
y.prototype.XDD = function() {};
y.prototype.constructor = y;
var rect = new y(1, 2);
选项 2 Object.setPrototypeOf()
function x(x, y) {
this.x = x;
this.y = y;
}
x.prototype.XDD = function() {};
function y(c, r) {
x.call(this, 1, 2);
this.r = r;
this.c = c;
}
y.prototype.YDD = function() {};
y.prototype.XDD = function() {};
Object.setPrototypeOf(y.prototype, x.prototype);
var rect = new y(1, 2);
它们之间有什么区别?。还有比这些更好的解决方案吗?。
最佳答案
根据 MDN docs :
Changing the [[Prototype]] of an object is, by the nature of how modern JavaScript engines optimize property accesses, currently a very slow operation in every browser and JavaScript engine. In addition, the effects of altering inheritance are subtle and far-flung, and are not limited to simply the time spent in the Object.setPrototypeOf(...) statement, but may extend to any code that has access to any object whose [[Prototype]] has been altered.
Because this feature is a part of the language, it is still the burden on engine developers to implement that feature performantly (ideally). Until engine developers address this issue, if you are concerned about performance, you should avoid setting the [[Prototype]] of an object. Instead, create a new object with the desired [[Prototype]] using Object.create().
性能比较(2019 年 2 月 14 日): https://gist.github.com/calebmer/c74e2a7941044e5f28b8#gistcomment-2836415
简而言之,当极度 规模更大。
在 JS 中设置对象的原型(prototype)还有许多其他方法(例如不推荐使用 Object.prototype.__proto__
),但如今(2019 年 10 月)最推荐的方法似乎是使用 ES6 class
,supported大多数现代浏览器。虽然有基准(如:this)表明 ES6 类和 super()
比对应的 ES5 慢,但它使您的代码更清晰,尤其是对于使用其他 OOP 语言的人而言。
关于javascript - 扩展 Object.setPrototypeOf() 与 Object.create,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58377377/