比方說,我有這樣的父類Vector2
定義如下:在JavaScript
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
,像這樣的aditional的能力:
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;
}
}
});
最後,我有一個代碼片段,創建了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
方法來創建新實例不管當前類是不是泛型?
最近做了太多的python。大聲笑 –
好你拒絕它。我只是測試和學到了一些東西。我爲我的無知道歉。 –
沒問題。 ;-) – trincot