所以我想知道下面代码中的两个调用之间的区别:我的理解是,一旦我使用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
将是undefined
或window
,这取决于您是否在strict mode
中。