没有 child.prototype = new Parent(); 的 Javascript 继承;
我正在研究 javascript 原型链继承,并且遇到了这个有趣的行为。
我有一个父类和一个子类
//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(); 并且仍然继承父类。
任何人都可以帮我解释一下这个场景吗?
I was playing around with javascript prototype chain inheritance and i came accross this funny behaviour.
I have a parent class and a child class
//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);
and i get the output as
**>child**
Constructor value in parent class 100
tguha ----> parent, val 200
and nowhere i'm doing //child.prototype = new parent();
and still the parent class is inherited.
Could anyone help me by explaining this scenario please.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这段代码中没有出现原型这个词。所以什么都没有被继承。您创建一个新的
child
,然后在该新的child
上显式运行parent
构造函数。然后,parent
构造函数向新的child
添加一个方法。如果您将
getObjWithParam
放在parent.prototype.getObjWithParam
上,那么您会发现它不会保留。The word prototype does not appear in this code. So nothing is being inherited. You create a new
child
and then explicitly run theparent
constructor function on that newchild
. Theparent
constructor function then add a method to to the newchild
.If you put
getObjWithParam
onparent.prototype.getObjWithParam
instead then you will see that it will not carry over.您在子构造函数中调用父构造函数。因为父构造函数设置了
this.getObjWithParam = function[...]
它也会为子构造函数设置它。请注意,这与原型无关。通过调用
parent.call(a, [...])
,您可以调用父函数并将作用域设置为a
。这意味着对this
所做的任何修改也会对a
进行(因为它是同一个对象)。You invoke parent constructor in child constructor. Because parent constructor sets
this.getObjWithParam = function[...]
it'll also set it for child. Notice that this has nothing to do with prototype.By invoking
parent.call(a, [...])
you invoke parent function and set scope toa
. That means any modification made tothis
is also made toa
(because it's the same object).将 Parent.param_1 和 Parent.getObjWithParam 分配给 childObj。这与继承无关。考虑这个公式:
这里将 foo 作为范围传递给 .call(),因此属性被分配给 foo。
Assigns Parent.param_1 and Parent.getObjWithParam to childObj. This has nothing to do with inheritance. Consider this formulation:
here you are passing foo as a scope to .call() thus the properties are assigned to foo.