The most important thing to understand is that a function object does not have a fixed this value — the value of this changes depending on how the function is called. We say that a function is invoked with some a particular this value — the this value is determined at invocation time, not definition time.
- If the function is called as a “raw” function (e.g., just do
someFunc()),thiswill be the global object (windowin a browser) (orundefinedif the function runs in strict mode). - If it is called as a method on an object,
thiswill be the calling object. - If you call a function with
callorapply,thisis specified as the first argument tocallorapply. - If it is called as an event listener,
thiswill be the element that is the target of the event. - If it is called as a constructor with
new,thiswill be a newly-created object whose prototype is set to theprototypeproperty of the constructor function. - If the function is the result of a
bindoperation, the function will always and forever havethisset to the first argument of thebindcall that produced it. (This is the single exception to the “functions don’t have a fixedthis” rule — functions produced bybindactually do have an immutablethis.)