javascript - 为什么另一个对象中的 Parent.call(this) 可以工作?

标签 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 不是指的是子对象吗? 请各位javascript新手指教,谢谢!

最佳答案

您正在使用call不是bind

Call 的一个用途是链接构造函数(类似于在 JAVA 等 OOP 语言中从子构造函数中执行 super())。子构造函数被调用,进而从子上下文中创建父对象。

但是,Bind 将为该函数设置所需的 this

按照建议,可以在 javascript 中找到 this 的解释 in this blog 以及 Stackoverflow question

关于javascript - 为什么另一个对象中的 Parent.call(this) 可以工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41588279/

相关文章:

javascript - 有没有办法同时使用 onmouseover 和 onmousedown ?

javascript - 检查 Titanium 中的空 json

javascript - 为什么在 Angular 2 中导入服务时需要 () ?

javascript - javascript 上的 http 请求的计时问题

javascript - chrome.hid.send 第二次使用失败

Matlab OOP - 重载大小()

c++ - 如何让策略类实现虚函数?

actionscript-3 - 如何正确扩展 AS3 Point 类?

php - 合并后代对象的数组属性

python - 对象继承和嵌套 cmd