为什么Parent.call(this)在另一个对象中有效?

时间:2017-01-11 10:25:04

标签: javascript oop

function Parent(){ 
this.name = "parent";
console.log("this gets executed");
}
function Child(){
 Parent.call(this) // doesnt the this here belongs to the child object?
}
var o = new Child();

为什么子对象中的this会调用父构造函数? this是否引用子对象? 请指教noob javascripter谢谢!

2 个答案:

答案 0 :(得分:2)

您使用的是call而不是bind

Call的一个用途是构造函数(类似于在JOPA等OOP语言中从子构造函数中执行super())。调用子构造函数,然后从Child上下文中创建Parent对象。

然而,绑定会为函数设置所需的this

根据建议,可以找到javascript中this的解释in this blog 以及Stackoverflow question

答案 1 :(得分:1)

this仅引用子对象。

这里你在Parent的上下文中调用this函数(即子对象)。

Parent.call(this)Parent()类似,唯一的区别是调用方法的上下文。