【发布时间】:2012-01-31 20:01:29
【问题描述】:
我是 JavaScript 世界的新手,在尝试原型链继承时遇到了这个奇怪的问题。
我有 3 节课
//class parent
function parent(param_1){
this.param = param_1;
this.getObjWithParam = function(val){
console.log("value in parent class "+val);
console.log("Constructor parameter : "+this.param);
};
};
//class child
function child(param_1){
this.constructor(param_1);
this.getObjWithParam = function(val){
console.log("value in child class "+val);
val = Number(val)+1;
child.prototype.getObjWithParam.call(this, [val]);
};
};
child.prototype = new parent();
//class grandChild
function grandChild(param_1){
this.constructor(param_1);
};
grandChild.prototype = new child();
var gc = new grandChild(666);
gc.getObjWithParam(0);
首先,我想将参数传递给父类的构造函数,就像它们在其他 OO 语言中调用 super(args) 的方式一样。
所以this.constructor(param_1); 非常适合这个目的。
但是,输出显示为
value in parent class 0
Constructor parameter : 666
这表明,grandChild 类跳过了原型链,而不是调用 child() 类的 getObjWithParam(),而是调用了父类的 getObjWithParam()。
有人知道这里出了什么问题吗?
注意: 我想补充两个发现,第二个是重要的。 --> 如果我尝试通过
找到grandChild类的构造函数console.log(gc.constructor)
我得到的输出是
function parent(param_1){
this.param = param_1;
this.getObjWithParam = function(val){
console.log("value in parent class "+val);
console.log("Constructor parameter : "+this.param);
};
}
这不是我所期望的。我期待看到子类。
-->如果我尝试在 child() 和 grandChild() 类中评论 //this.constructor(param_1);,代码将完全按预期工作。
谁能解释一下这个现象。
此外,如果有人能提出解决方法,我们将不胜感激。
谢谢
【问题讨论】:
标签: javascript constructor parameter-passing superclass