“this” and function invocation patterns JS (Part II)
Will also review new features added in ES5 and we talk about some cases derived from the ES6: arrow functions.
Let’s dig into it.
3# The constructor invocation pattern
As seen above the method
getName() prints the correct value Batman, so the
this value is bound to the batman
object. Why? Because when invoking a function with
new, a new object is created with a hidden link to the value of the functions
prototype member and
this is bound to that new object and not to the global object (
window in the browser) as you could see in the previous example.
4# The apply invocation pattern
this when we invoke a function. Those methods are
apply. The only difference between these two methods is how the params are passed to the function. The
apply method accepts params as array and
call as argument list.
Let’s use this new superpower to fix the problem with this in the previous example from the function invocation pattern.
ECMAScript 5 introduced the new
bind method to change the value of
this when a function is invoked. With this method you can pass an object, the difference with the previous
apply methods is that
bind creates a new function with the same body and scope than the passed function but where
this occurs in the original function.
this is permanently bound to the first argument of
Do you remember the first example? Let’s try this new method:
If you run the previous code you will see that the output for the
console.log(baz()) is an empty string. Why? You are assigning an object method to a variable and after that, you are invoking that new variable (
baz in the example) as a function so the value of
this is bound to the global scope (
window object in the browser).
Let’s run again while using
The result of the execution in the
console will tell us what value has this in every execution.
We can fix it using the
We could talk more about this topic, how
this works in
arrow functions and if you are able to use
bind to change the value
this is bound to. But this could be the topic of another blog post.
Did you find some other great strategies of your own? Let me know in comments.
And if you enjoyed this post, I’d be very grateful if you’d help me share it.
Thanks for reading.
List of resources