To understand why it is returning undefined
instead of ali
, you have to understand JavaScript binding.
If you are accessing a method through a reference instead of directly through its owner object, as you are doing, the method loses its implicit binding, and this
stops referencing its owner object and goes back to its default binding, meaning the global object (or undefined
in strict mode).
Ultimately, what matters is the manner in which the function is invoked.
See below for more information (there are exceptions, but it can be generally summarized as the following):
Breakdown from YDKJS: Determining this
Now, we can summarize the rules for determining this from a function call's call-site, in their order of precedence. Ask these questions in this order, and stop when the first rule applies.
Is the function called with new (new binding)? If so, this is the newly constructed object.
Is the function called with call or apply (explicit binding), even hidden inside a bind hard binding? If so, this is the explicitly specified object.
- var bar = foo.call( obj2 )
Is the function called with a context (implicit binding), otherwise known as an owning or containing object? If so, this is that context object.
Otherwise, default the this (default binding). If in strict mode, pick undefined, otherwise pick the global object.
Note: In ES6, this
is the lexical this
for fat arrow functions =>
and with object short hand notation (e.g., sampleMethod() {}
), meaning that this
takes on the outer context as reference.