Arrow Functions Capture Lexical this

Arrow callbacks reuse the this of their defining scope: plain function callbacks lose it in strict mode, arrow callbacks keep the surrounding object.

JavascriptResilience

Code

javascriptsnippet
31 lines
// 箭头函数没有自己的 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();

Output

Captured from a sandboxed run of this snippet in the build pipeline.

arrow method count: 1
arrow method count: 2
plain function sees this as: undefined
arrow sees label as: batch-1

How it works

Arrow Functions Capture Lexical this keeps everything in the class Counter.

Top-level bindings batch, counter hold the demo state — nothing sits inside a function scope.

Applying it

The demo output is labeled (plain function sees this as:, arrow sees label as:, arrow method count:); each label names the call that printed it.

Statements that matter

setTimeout(() => {
  console.log('arrow sees label as:', this.label);
}, 20);
this.count += 1;

Interactive Tools for This Topic

FAQ

What has to be installed first?
Nothing — the runtime itself provides everything the code touches. Its state lives in module-level bindings: `batch`, `counter`.