我知道两种继承函数构造器的方法。
选项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
。 - georgclass
关键字,因为它是基于class 和 object
的,而Object.create
则是基于原型继承
的,只适用于某些情况。 - Satyam PathakObject.setPrototypeOf()
也意味着您可能希望在事件之后更改原型。我想不出一个真实的例子来解释为什么需要这样做,但是就是这样。 - Manngo