This is one part of a two part series on how to use bind(), call() and apply() in your javascript code.
How and where you call a function in javascript matters a lot, yeah a lot. One reason being that it defines what the value of 'this' will be in that function's execution context.
Javascript gives us the ability to decide what 'this' would point to each time the function is executed. What this means is that we can tell the javascript engine what object we want the method(function) to be called on, each time it's executed. Cool right! Let's proceed.
You may have heard of bind, call or apply methods, have you? Well their primary purpose is to help you decide what you want 'this' to point to while executing a function. bind is a method on the Function object(Function.prototype.bind), and is available by default as a method on functions you create since functions have the Function object as their prototype.
bind(this, args)
Whenever bind is called, it returns a 'new function', this function has it's 'this' value set to the object you provided when bind was called. This means each time this new function will be executed, the 'this' in the execution context that will be created, would always point at the object you passed in when calling bind.
const user = {
name: 'sage',
balance: 1000
};
const getBalance = () => this.balance;
console.log(getBalance()); // undefined
Since the function was called in global scope, its 'this' pointed to the global object(Window object in web browsers). And balance was not defined as a property on the global object so it returned undefined.
Now let's bind the function's 'this' to a different object and see how it goes.
const newGetBalance = getBalance.bind(user);
console.log(newGetBalance()); // 1000
So what this means is that each time you call the new function we got from the bind call(newGetBalance), a new execution context will be created, and in that execution context, the value of 'this' would always be the user object that we provided. That's flexible if you ask me.
bind also accepts other parameters, in addition to the parameters the function accepts by default. These new parameters to the bind call will precede the original ones the function accepts.
Top comments (0)