admin管理员组文章数量:1431019
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
2 Answers
Reset to default 8The .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
本文标签: Hard binding in javascriptStack Overflow
版权声明:本文标题:Hard binding in javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745515160a2661492.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论