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
不是指的是子对象吗?
请各位javascript新手指教,谢谢!
最佳答案
Call 的一个用途是链接构造函数(类似于在 JAVA 等 OOP 语言中从子构造函数中执行 super()
)。子构造函数被调用,进而从子上下文中创建父对象。
但是,Bind 将为该函数设置所需的 this
。
按照建议,可以在 javascript 中找到 this
的解释 in this blog
以及 Stackoverflow question
关于javascript - 为什么另一个对象中的 Parent.call(this) 可以工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41588279/