javascript - 全局上下文中的 Javascript this 不起作用,或者看起来像 console.log 工作但使用 ref 不起作用
问题描述
所以我想知道下面代码中两个调用之间的区别:我的理解是,一旦我使用 user.credential.getID 获得 ref 功能,我应该能够执行它并且在 console.log(user. credentials.getID());// 有效
const user = {
id: 551,
name: 'Tom',
getID() {
return this.id;
},
credentials: {
id: 120,
name: 'Jack',
getID() {
return this.id;
}
}
}
var getId = user.credentials.getId;
console.log(getId); // undefined why?
console.log(user.credentials.getID()); // it works
解决方案
只需记住一条规则,this
即从调用函数的位置获取其值。如果你从一个对象调用一个函数,例如obj.func()
,this
将是obj
. 例如,如果您从任何地方调用它func()
,this
将是undefined
或window
,这取决于您是否在strict mode
。
推荐阅读
- angular - 使用 Mat-Select 实现默认值的 Angular Material Stepper
- makefile - GNU make - 不使用隐式规则,但使用静态模式规则
- amazon-s3 - AWS S3 和 PowerBI
- reactjs - index.js:1 警告 findDOMNode
- android - 父片段被共享元素转换破坏
- c++ - 使用 std::allocator C++ 时字符串和 int 之间的区别
- python - 在熊猫数据框中查找嵌套列
- javascript - 强制标签导航内的 div 显示在所有其他页面内容的顶部
- asynchronous - Web 应用程序如何受并发影响?
- javascript - 为什么 requestMIDIAccess 在本地工作而不是远程工作?