When you call a function, JavaScript sets this
according to the call site:
Call style | Example | Value of this |
---|---|---|
Method call | obj.method() |
this is obj |
Simple call | func() |
In non-strict mode: this is the global object (window in browsers, global in Node). In strict mode: undefined . |
Constructor call | new Func() |
this is a new object created and linked to Func.prototype |
Bound call | func.call(obj, ...) or func.apply(obj, ...) |
this is explicitly set to obj |
Arrow function | () => { ... } |
Arrow functions don’t have their own this —they close over the this from the surrounding scope. |
Notes
The this
value is not permanently stored in a function in JavaScript. It’s completely ephemeral, decided fresh on each call based on how the function is invoked.
The only case where a function “remembers” its this
is if you used bind()
or an arrow function. (bind()
can set this
to absolutely any value—it doesn’t have to be an object.)
If you write let f = obj.method
and then call f()
it has no memory of the object. Tying the this
onto the function only happens in methodized calls like obj.m()
If you wanted f to remember obj as this, you’d have to explicitly bind it, e.g. let f_bound = obj.m.bind(obj);