我正在研究 javascript 原型(prototype)链继承,并且遇到了这个有趣的行为。
我有一个父类和一个子类
//class parent
function parent(param_1) {
this.param_1 = param_1;
this.getObjWithParam = function(val) {
console.log(this);
console.log("Constructor value in parent class " + this.param_1);
console.log("tguha ----> parent, val " + val);
};
};
//class child
function child(param_1) {
parent.call(this, [ param_1 ]);
};
var childObj = new child(100);
childObj.getObjWithParam(200);
我得到的输出为
**>child**
Constructor value in parent class 100
tguha ----> parent, val 200
我无处可做//child.prototype = new Parent(); 并且仍然继承父类。
有人可以帮我解释一下这个场景吗?
最佳答案
这段代码中没有出现原型(prototype)这个词。所以什么都没有被继承。您创建一个新的 child
,然后在该新的 child
上显式运行 parent
构造函数。然后,parent
构造函数向新的 child
添加一个方法。
如果您将 getObjWithParam
放在 parent.prototype.getObjWithParam
上,那么您会发现它不会继承。
关于没有 child.prototype = new Parent(); 的 Javascript 继承;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8739803/