实现说明
Counter是实现的全部所在。
演示用的数据放在这几个模块级绑定中:batch、counter。
使用要点
- 直接运行文件,输出会带上标签,比如
plain function sees this as:、arrow sees label as:、arrow method count:——输出的每一行都能指回产生它的那次调用。
常见问题
运行前要先安装什么?
什么都不用额外装——运行时自带了代码所需的一切。 状态都挂在模块顶层:batch、counter。
核心语句
setTimeout(() => {
console.log('arrow sees label as:', this.label);
}, 20);
this.count += 1;
代码示例
// 箭头函数没有自己的 this:它沿用定义处的词法 this
const batch = {
label: 'batch-1',
start() {
// 普通函数回调:ESM 严格模式下 this 是 undefined
setTimeout(function () {
const seen = this === undefined ? 'undefined' : this.label;
console.log('plain function sees this as:', seen);
}, 10);
// 箭头函数回调:this 沿用 start() 的 this,即 batch
setTimeout(() => {
console.log('arrow sees label as:', this.label);
}, 20);
},
};
batch.start();
// 类字段同理:箭头函数把实例绑定进回调
class Counter {
count = 0;
tick = () => {
this.count += 1;
console.log('arrow method count:', this.count);
};
}
const counter = new Counter();
counter.tick();
counter.tick();