【发布时间】:2019-10-14 12:58:14
【问题描述】:
我知道继承函数构造函数的两种方法。
选项 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);
它们之间有什么区别?。还有比这些更好的解决方案吗?。
【问题讨论】:
-
回答最后一个问题,是的,有:
class Foo extends Bar -
Upto Preference -JS 基于
prototypal inheritance、Object.create,仅此一个。但对class and object更有经验的人更喜欢class关键字 -
尽管存在性能问题,但使用
Object.setPrototypeOf()也表明您可能希望在事件之后 更改原型。我想不出一个现实的例子来说明为什么你需要这样做,但是你去吧。
标签: javascript