window.identity = 'The Window';
let object = {
identity:'My Object',
getIdentityFunc(){
return function(){
return this.identity;
}
}
}
console.log(object.getIdentityFunc()());
- 内部函数永远不可能直接访问外部函数的this和arguments这两个变量,所以上述代码中的this指向了window对象。
window.identity = 'The Window';
let object = {
identity:'My Object',
getIdentityFunc(){
let that = this;
return function(){
return that.identity;
}
}
}
console.log(object.getIdentityFunc()());
- 在定义匿名函数之前,先把外部函数的this保存到变量that中,然后在定义闭包时,就可以让他访问到that。
window.identity = 'The Window';
let object = {
identity:'My Object',
getIdentity(){
return this.identity;
}
};
console.log(object.getIdentity());
console.log((object.getIdentity)());
console.log((object.getIdentity = object.getIdentity)());
- 前面两次调用的返回结果是My Object,后面调用的返回结果是The window,因为赋值表达式的值是函数本身,this值不再与任何对象绑定,所以返回的是The Window。