我是 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);
首先,我想将参数传递给父类的构造函数,就像它们在其他面向对象语言中调用 super(args) 所做的那样。
所以this.constructor(param_1);
相当适合目的。
但是,输出为
value in parent class 0
Constructor parameter : 666
这表明,类 grandChild 跳过了原型链,并且没有调用 child() 类的 getObjWithParam() ,而是调用了父类的 getObjWithParam() 。
有谁知道这里出了什么问题吗?
NB:我想补充两个发现,第二个是重要的。-->如果我尝试通过以下方式找到 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);
};
}
这并不完全是我所期望的。我期待着看到孩子们的班级。
-->如果我尝试comment //this.constructor(param_1);
在 child() 和 grandChild() 类中,代码完全按照预期工作。
谁能解释一下这个现象。
另外,如果有人能提出解决方法,我们将不胜感激。
Thanks