JavaScript this: Call Sites, Binding Rules, and Arrow Functions

this is not “the object a function belongs to.” In JavaScript, its value is usually determined by how a function is called, not where the function was written.

Method calls

1
2
3
4
5
6
7
8
const cat = {
name: 'Milo',
speak() {
return this.name;
},
};

cat.speak(); // "Milo"

The receiver before the dot becomes this. But extracting the function removes that receiver:

1
2
const speak = cat.speak;
speak(); // undefined in strict mode; global behavior varies by environment

Explicit binding

call, apply, and bind select the receiver explicitly:

1
2
3
4
5
6
7
function greet(greeting) {
return `${greeting}, ${this.name}`;
}

greet.call(cat, 'Hello');
greet.apply(cat, ['Hello']);
const greetCat = greet.bind(cat);

bind returns a new function whose this is fixed.

Constructor calls

With new, JavaScript creates an object and binds it as this inside the constructor:

1
2
3
4
5
function User(name) {
this.name = name;
}

const user = new User('Hudson');

Arrow functions

Arrow functions do not create their own this. They capture it lexically from the surrounding scope:

1
2
3
4
5
6
7
8
const counter = {
value: 0,
start() {
setInterval(() => {
this.value += 1;
}, 1000);
},
};

That makes arrows useful for callbacks inside methods, but usually wrong as object methods when dynamic receiver binding is required.

Global context is environment-dependent

At the top level of a browser classic script, this may be window. In an ES module, top-level this is undefined. In Node.js CommonJS modules, top-level this is not the global object. Therefore “this alone is always global” is not a portable rule.

A practical decision tree

  1. Called with new? this is the new instance.
  2. Called with call, apply, or a bound function? Use the explicit receiver.
  3. Called as object.method()? this is object.
  4. Arrow function? Inherit this from the surrounding scope.
  5. Plain function call? undefined in strict mode; legacy non-strict behavior may use the global object.

The keyword is not random. It is just context-sensitive enough to punish vague mental models.

References