我试图让一个 JavaScript 对象使用另一个对象的构造函数的“this”赋值,并假设所有对象的原型函数。这是我试图完成的一个例子:
/* 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”(即不必重复this.$* = *
ObjY 的构造函数中的所有赋值)并让 ObjY 假定 ObjX.prototype 的想法。
我的第一个想法是尝试以下方法:
function ObjY(a,b,c) {
this.prototype = new ObjX(a,b*12);
}
理想情况下,我想以原型的方式学习如何做到这一点(即不必使用任何像Base2这样的“经典”OOP 替代品)。
值得注意的是,ObjY 将是匿名的(例如factory['ObjX'] = function(a,b,c) { this = ObjX(a,b*12); ... }
)——如果我的术语正确的话。
谢谢你。