Javascript 调用() &应用()与绑定()? [英] Javascript call() & apply() vs bind()?
本文介绍了Javascript 调用() &应用()与绑定()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经知道 apply
和 call
是类似的函数,它们设置了this
(函数的上下文).
区别在于我们发送参数的方式(手动 vs 数组)
问题:
但是我什么时候应该使用 bind()
方法?
var obj = {x: 81,getX:函数(){返回 this.x;}};警报(obj.getX.bind(obj)());警报(obj.getX.call(obj));警报(obj.getX.apply(obj));
.bind
允许您设置 this
值 now 同时允许您在将来执行函数 >,因为它返回一个新的函数对象.
I already know that apply
and call
are similar functions which setthis
(context of a function).
The difference is with the way we send the arguments (manual vs array)
Question:
But when should I use the bind()
method ?
var obj = {
x: 81,
getX: function() {
return this.x;
}
};
alert(obj.getX.bind(obj)());
alert(obj.getX.call(obj));
alert(obj.getX.apply(obj));
解决方案
I created this comparison between function objects, function calls, call/apply
and bind
a while ago:
.bind
allows you to set the this
value now while allowing you to execute the function in the future, because it returns a new function object.
这篇关于Javascript 调用() &应用()与绑定()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文