Javascript this 在全局上下文中不起作用,或者看起来 console.log 起作用但使用 ref 不起作用
Javascript this in global context doesn't work, or seems like console.log works but using ref doesn't work
所以我想知道下面代码中两个调用之间的区别:
我的理解是,一旦我使用 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
中。
所以我想知道下面代码中两个调用之间的区别: 我的理解是,一旦我使用 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
中。