JavaScript 函数闭包、立即执行函数与异步编程
1. 闭包中的 this 对象
在闭包中使用 this 对象会引入一些复杂的行为。当函数不是使用箭头语法定义时, this 对象在运行时根据函数执行的上下文进行绑定:
- 在全局函数中使用时,在非严格模式下 this 等于 window ,在严格模式下为 undefined 。
- 当作为对象方法调用时, this 等于该对象。
匿名函数在这种上下文中不绑定到对象,这意味着除非在严格模式下执行(此时 this 为 undefined ),否则 this 对象指向 window 。
示例代码
window.identity = 'The Window';
let object = {
identity: 'My Object',
getIdentityFunc() {
return function() {
return this.identity;
};
}
};
console.log(object.getIdentityFunc()()); // 'The Window'
在上述代码中,虽然我们期望匿名
超级会员免费看
订阅专栏 解锁全文
1042

被折叠的 条评论
为什么被折叠?



