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谢谢!
答案 0 :(得分:2)
Call的一个用途是链构造函数(类似于在JOPA等OOP语言中从子构造函数中执行super()
)。调用子构造函数,然后从Child上下文中创建Parent对象。
然而,绑定会为函数设置所需的this
。
根据建议,可以找到javascript中this
的解释in this blog
以及Stackoverflow question
答案 1 :(得分:1)
this
仅引用子对象。
这里你在Parent
的上下文中调用this
函数(即子对象)。
Parent.call(this)
与Parent()
类似,唯一的区别是调用方法的上下文。