Why does a method work on an object but fail after you assign it to a variable? In JavaScript, `this` is an implicit function parameter: its value can depend on how a function is called, not just where it was defined. Unlike the usual class-method intuition from Java or C#, a method does not necessarily keep its original instance as `this`. section 6.0 section 6.1
For a non-arrow function, check the invocation:
- A standalone call normally has `this === undefined` in strict mode. Without strict mode, `this` is the global object. section 6.2.1
- A method call uses the object it is called on. Assigning the method to a variable and calling that variable loses this method context. section 6.2.2 section 6.1
- A call with `new` uses the newly constructed object. `call` and `apply` use the context supplied as their first argument; `bind` creates a function with a fixed context. section 6.4
Listing 6.2 The differences between function and method invocations
"use strict"; #A
function whatsMyContext() { #B
return this; #B
} #B
console.assert(whatsMyContext() === undefined, "Context is undefined");
const ninja1 = { #C
getMyThis: whatsMyContext, #C
}; #C
console.assert(ninja1.getMyThis() === ninja1, "Working with 1st ninja");
The same function returns `undefined` when called alone in strict mode, then returns the object when called through its method property. The function did not change; the invocation did. section 6.2.2
Arrow functions take `this` from their surrounding context instead of receiving it from the call. This makes them useful for callbacks that must retain an enclosing context: `call`, `apply`, and `bind` cannot replace an arrow function’s `this`. But an object literal does not create a lexical context. An arrow function written as an ordinary object’s handler therefore does not acquire that object as `this`; a wrapper that calls the handler as a method can preserve the intended method invocation. section 6.3.2






