最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Hard binding in javascript - Stack Overflow

programmeradmin2浏览0评论

Can anyone explain me on how 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 wrap foo.call(obj) inside another function?. We can use it directly right?.

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

Can anyone explain me on how 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 wrap foo.call(obj) inside another function?. We can use it directly right?.

setTimeout(foo.call(obj), 100); // still results in 2.
Share Improve this question asked Dec 6, 2014 at 18:46 ShaneShane 5,69715 gold badges57 silver badges82 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

The .call (and .apply) methods simply let you manually set the value of this in the function being invoked.

So when you do foo.call(obj), the value of this in foo will be obj.

As to the setTimeout, what you're doing is calling it immediately instead of waiting for 100ms. Change it to 10000, and you'll see more clearly it doesn't wait.

So that's why the function is needed. You need to pass a function to setTimeout, and it will get invoked after the duration you provide.


There's also the .bind() method that creates a new function with its this value permanently bound to the first argument you provide. So that would actually be a hard binding example

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

So in that example, a function is returned that will always have obj set as the this value. So now that setTimeout is being passed a function, it will be invoked after the given duration.

You can also bind arguments to the function. All arguments passed to .bind() after the first argument will be permanently bound to the returned function so that any arguments passed to that function will be placed after the bound ones.

You don't need setTimeout to achieve hard binding.

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

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

OriginalFoo now has the reference to foo

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

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

foo(); // returns 10
foo.call(obj2); //returns 10 even when obj2 passed as arg
发布评论

评论列表(0)

  1. 暂无评论