javascript “调用/应用”和“绑定”有什么区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15677738/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
what's the difference between 'call/apply' and 'bind'
提问by bennyrice
var obj = {
x: 81,
getX: function() {
console.log( this.x)
}
};
var getX = obj.getX.bind(obj);//use obj as 'this';
getX();//81
var getX = function(){
obj.getX.apply(obj);
}
getX();//also 81
The use of bind and call/apply look very similar, I want to know what's the difference between them.The two getX Function above is the same?
bind和call/apply的使用看起来很相似,我想知道它们有什么区别。上面两个getX函数是一样的吗?
回答by Quentin
bind
returns a function which will act like the original function but with this
predefined. It is usually used when you want to pass a function to an event handler or other async callback.
bind
返回一个函数,它的行为类似于原始函数,但具有this
预定义。当您想将函数传递给事件处理程序或其他异步回调时,通常会使用它。
call
and apply
will call a function immediately letting you specify both the value of this
and any arguments the function will receive.
call
并将apply
立即调用一个函数,让您指定this
函数将接收的值和任何参数。
Your second example defines an anonymous function which calls apply
. This is a common pattern; bind
provides a standard implementation of that which allows you to do it with a simple function call (thus being quicker and easier to write).
您的第二个示例定义了一个匿名函数,该函数调用apply
. 这是一种常见的模式;bind
提供了一个标准实现,它允许您通过一个简单的函数调用来完成它(因此编写起来更快更容易)。
回答by techfoobar
.call()
- calls the same function with the specified arguments
.call()
- 使用指定的参数调用相同的函数
.apply()
- calls the same function with the arguments specified in an array
.apply()
- 使用数组中指定的参数调用相同的函数
.bind()
- creates a new function with the same function body, with a preset value of this
(the first argument) and returns that function.
.bind()
- 创建一个具有相同函数体的新函数,预设值为this
(第一个参数)并返回该函数。
In all cases, the first argument is used as the value of this
inside the function.
在所有情况下,第一个参数用作this
函数内部的值。
回答by T.J. Crowder
The difference is how you make the call. If you've used bind
to get back a function with a bound this
value, you just call the function:
区别在于您如何拨打电话。如果您曾经使用bind
绑定this
值取回函数,则只需调用该函数:
getx();
If you don't have a bound function, and you want to set this
, you do so with call
or apply
:
如果您没有绑定函数,而您想设置this
,则使用call
or进行设置apply
:
someFunction.call(objectToUseAsThis, arg1, arg2);
// or
someFunction.apply(objectToUseAsThis, [arg1, arg2]);
Note that if you have a bound function (like your getX
), using call
on it is pointless, because the this
you supply will just get overridden by the bound this
. (Using apply
might still be useful, if you have an array of values you want to ass as arguments.)
请注意,如果您有一个绑定函数(如您的getX
),则使用call
它是毫无意义的,因为this
您提供的将被 bound 覆盖this
。(使用apply
可能仍然有用,如果您有要作为参数的值数组。)