我试图让一个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