Javascript Prototype Chaining超类构造函数和方法调用

Tir*_*tha 6 javascript constructor parameter-passing superclass

我是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);
Run Code Online (Sandbox Code Playgroud)

首先,我想将一个参数传递给父类的构造函数,就像它们通过在其他OO语言中调用super(args)一样.所以this.constructor(param_1);非常适合这个目的.

但是,输出结果为

value in parent class 0
Constructor parameter : 666
Run Code Online (Sandbox Code Playgroud)

这表明,类grandChild已跳过原型链,而不是调用child()类的getObjWithParam(),而是调用了父类的getObjWithParam().

有谁知道这里出了什么问题?

注意: 我想添加2个更多的发现,第二个是重要的发现. - >如果我试图找到grandChild类的构造函数

console.log(gc.constructor)
Run Code Online (Sandbox Code Playgroud)

我得到的输出是

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);
    };
}
Run Code Online (Sandbox Code Playgroud)

这不是我预期的事情.我期待看到孩子班.

- >如果我尝试在child()和grandChild()类中进行注释 //this.constructor(param_1);,则代码完全按预期工作.

任何人都可以解释这个现象.

此外,如果有人能提出解决方法,我们将非常感激.

谢谢

m0s*_*0sa 4

在构造函数中声明 this.SOME_METHOD 不会将其添加到类型的原型中。原型函数需要单独声明,例如:

//class parent
function parent(param_1){
    console.log("parent " + param_1);
    this.param = param_1;
}

parent.prototype.getObjWithParam = function(val) {
    console.log("value in parent class "+val);
    console.log("Constructor parameter : "+this.param);
};

//class child
function child(param_1){
    console.log("child " + param_1);
    this.constructor(param_1);
}
child.prototype = new parent();
child.prototype.getObjWithParam = function(val) {
    console.log("value in child class "+val);
    val = Number(val)+1;
    parent.prototype.getObjWithParam.call(this, [val]);    
}

//class grandChild
function grandChild(param_1){
    console.log("grandChild " + param_1);
    this.constructor(param_1);
}
grandChild.prototype = new child();


var gc = new grandChild(666);
gc.getObjWithParam(0);
Run Code Online (Sandbox Code Playgroud)

我建议您阅读这篇文章,以更深入地了解原型如何在 javascript 中工作。