我試圖讓一個JavaScript對象使用另一個對象構造函數的「this」賦值,並假設所有對象的原型功能。這裏就是我試圖完成的例子:使用「this =」的Javascript函數給出了「賦值中無效的左側」
/* The base - contains assignments to 'this', and prototype functions
*/
function ObjX(a,b) {
this.$a = a;
this.$b = b;
}
ObjX.prototype.getB() {
return this.$b;
}
function ObjY(a,b,c) {
// here's what I'm thinking should work:
this = ObjX(a, b * 12);
/* and by 'work' I mean ObjY should have the following properties:
* ObjY.$a == a, ObjY.$b == b * 12,
* and ObjY.getB == ObjX.prototype.getB
* ... unfortunately I get the error:
* Uncaught ReferenceError: Invalid left-hand side in assignment
*/
this.$c = c; // just to further distinguish ObjY from ObjX.
}
我會就如何有ObjY歸入物objx的任務,以「這個」你的想法感激(即不必重複所有this.$* = *
分配中ObjY的構造函數)並且ObjY假定ObjX.prototype。
我首先想到的是嘗試以下操作:
function ObjY(a,b,c) {
this.prototype = new ObjX(a,b*12);
}
理想我想了解如何在原型的方式做到這一點(即沒有使用任何的「經典」 OOP代用品像Base2)。
值得注意的是,ObjY將是匿名的(例如factory['ObjX'] = function(a,b,c) { this = ObjX(a,b*12); ... }
) - 如果我擁有正確的術語。
謝謝。
相關:[?爲什麼我不能指定一個新值「本」的原型函數(HTTP:// stackoverflow.com/q/9713323/1048572) – Bergi 2014-11-15 20:36:29