The actual error in your standard function
call is that subscribe
has its own context for this and it is not aware of myUserList
, thus its undefined in your template context. Previous examples demonstrate assigning var self = this;
or var that = this
prior to the call but you could also use a closure or potentially use bind()
to bind the outer this
to subscribe
. However, just use the arrow function unless you're curious.
Simply put, arrow functions preserve the context of this
, whereas standard functions could have the value of their this
context changed simply by the caller. Also note that the context of arrow functions can not be changed, for they are lexically scoped. Ergo, .call(), .apply() and .bind() would not work as intended on arrow functions. Remember that functions in JS are Objects, thus why we can call apply
, call
or bind
on a function. Although, callers changing the context of the callee function is typically for some object oriented reason, it does have applications in functional programming as well. Take notice that in the pattern Math.func() is a constructor, meant to be used as a static method vs creating an instance of the Math library like you would an Array, therefore the max() method is not on the prototype. If you were to use .apply() on an Array it would be Array.prototype.map(...).apply(ctx, [values])
note that because the Math library's max
function is a constructor context is irrelevant. Unfortunately, Math.max(..)
does not take an array, ergo historically a great way
to take an array of numbers and pass them into Math.max(..)
was to use apply(..
) without passing context like so:
// es5 way
var arr = [1, 2, 3, 4],
max;
// notice we use apply here to destructure the array
// will convert the arguments into a format usable by max
max = Math.max.apply(null, arr); // notice context is null
max => 4
In ES6+, you can something like this:
const arr = [1, 2, 3, 4];
// notice how simple this is, just spread the array
let max = Math.max(...arr);
max => 4
This is why you would see a lot of code early on that made use of these methods, and while this can seem confusing at first, it is also empowering in many ways. ES6+ fixes much of this with the arrow functions so that this
operates in a consistent manner. Although, there are still use cases for function expressions, such as you can not define a generator function using arrow functions (yet). I would recommend you checkout this link (javascript.info) resource - it offers amazing explanations of spread, rest, arrow functions, and practically everything else you can imagine.