Javascript 这在全局上下文中不起作用,或者看起来像控制台.log有效但使用 ref 不起作用



所以我想知道下面代码中的两个调用之间的区别:我的理解是,一旦我使用user.credential.getID获得ref函数,我就应该能够执行它,并且它在console.log(user.credients.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将是undefinedwindow,这取决于您是否在strict mode中。

相关内容

最新更新