In the previous post we discussed how - 'this' keyword works in JS.
But there was a problem we discovered;
Problem
when we call a function as a standalone object - or outside an object this will return the global object which is the window object in browsers, but we wanna return 'man' object (in this case)
Solution
using the bind function as shown below;
const man = {
name: "rick",
adventure() {
console.log(this);
}
};
const adventure_reference = man.adventure.bind(man);
adventure_reference();
Output;
Explanation
-
Functions in JS are objects, they have properties and methods we can use.
- this means adventure function in 'man.adventure' is an object and it has access to methods and properties - in this case we use bind () method
With the 'bind()' method we can set the value of 'this' permenantly.
When we call bind() under adventure() function we get a new function , And in that new function value of 'this' is based on the argument we pass in the bind method.
const adventure_reference = man.adventure.bind(what_we_pass_here_as_an_argument);
adventure_reference();
'what_we_pass_here_as_an_argument' will determine the value of this ,
so when what_we_pass_here_as_an_argument is 'man' object, the bind method will return a new instance of the adventure function and set 'this' to point to the man object.
Top comments (0)