【发布时间】:2017-07-21 21:33:51
【问题描述】:
假设我有这个父类Vector2 定义如下:
function Vector2 (x, y) {
this.x = x;
this.y = y;
}
Vector2.prototype.add = function(vec) {
console.log(Reflect.getPrototypeOf(this));
if (vec instanceof Vector2)
return new Vector2(this.x + vec.x, this.y + vec.y);
throw "This operation can only be performed on another Vector2. Recieved " + typeof vec;
};
Vector2 的扩展名为Size,它应该继承其父级的所有功能优势,并具有将x 和y 分别引用为w 和h 的附加能力,就像这样:
function Size(x,y) {
this.x = x;
this.y = y;
}
Size.prototype = new Vector2;
Size.prototype.constructor = Size;
Size.prototype._super = Vector2.prototype;
Object.defineProperties(Size.prototype, {
'w': {
get: function() {
return this.x;
},
set: function(w) {
this.x = w;
}
},
'h': {
get: function() {
return this.y;
},
set: function(h) {
this.y = h;
}
}
});
最后,我有一个代码 sn-p,它创建了两个 Size 的新实例,将它们加在一起,并尝试像这样从 w 属性中读取:
var s1 = new Size(2, 4);
var s2 = new Size(3, 7);
var s3 = s1.add(s2);
console.log(s3.w);
// 'undefined' because s3 is an instance Vector2, not Size
我如何修改Vector2 的add 方法来创建一个无论当前类的新实例而不是通用类?
【问题讨论】:
标签: javascript oop inheritance