所以我想知道以下代码中两个调用之间的区别:我的理解是,一旦我获得使用user.credential.getID的功能的引用,我就应该能够执行它,并且它在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
所以,我想知道下面代码中的两个调用之间的区别:我的理解是,一旦我使用user.credential.getID引用函数,我应该能够执行它,并且似乎可以执行...]]
只需记住一个规则,this
从调用函数的位置获取其值。如果从某个对象(例如obj.func()
)调用函数,则this
将为obj
。如果从任何地方调用它,例如func()
,则this
将是undefined
或window
,这取决于您是否在strict mode
中。