Hard binding in javascript

Can anyone explain to me how it hard binding

works in javascript ?.

function foo() {
    console.log(this.a);
}
var obj = {
    a: 2
};
var bar = function() {
    foo.call(obj);
};
bar(); // 2
setTimeout(bar, 100); // 

      

I am more interested in this function.

var bar = function() {
    foo.call(obj);
};

      

Why do we end up foo.call(obj)

inside another function

? We can use it directly right.

setTimeout(foo.call(obj), 100); // still results in 2.

      

+3


source to share


2 answers


Methods .call

(s .apply

) simply allow you to manually set the value this

in the called function.

So when you do foo.call(obj)

, the value this

in foo

will be obj

.

As for setTimeout

, you do it immediately instead of waiting for 100ms. Change it to 10000

and you will see that it won't wait.

So why is the function needed. You need to pass a function setTimeout

and it will be called after you provide.




There is also a method .bind()

that creates a new function with a value this

permanently bound to the first argument you provide. So this would actually be an example of hard binding

setTimeout(foo.bind(obj), 100);

      

So this example returns a function that will always have obj

both this value. So now when setTimeout

a function is passed, it will be called after the given duration.

You can also bind arguments to a function. All arguments are passed in .bind()

after the first argument is permanently bound to the returned function, so any arguments passed to that function will be placed after the bound ones.

+6


source


You don't need setTimeout to do hard binding.

function foo() {
    console.log(this.bar);
}

var obj1 = {bar:10};
var obj2 = {bar:5};
var originalFoo = foo;

      

OriginalFoo now has a link to foo



Now override the foo function and use originalFoo.call to set this context always as obj1

foo = function() {
    originalFoo.call(obj1);
}

foo(); // returns 10
foo.call(obj2); //returns 10 even when obj2 passed as arg

      

+1


source







All Articles