“调用/应用"和“绑定"有什么区别 [英] what's the difference between 'call/apply' and 'bind'
问题描述
var obj = {x: 81,getX:函数(){控制台.log(this.x)}};var getX = obj.getX.bind(obj);//使用obj作为'this';getX();//81var getX = 函数(){obj.getX.apply(obj);}getX();//也是81
bind和call/apply的用法看起来很像,我想知道它们有什么区别.上面两个getX函数是一样的吗?
bind
返回一个函数,该函数的行为与原始函数类似,但预定义了 this
.当您想将函数传递给事件处理程序或其他异步回调时,通常会使用它.
call
和 apply
将立即调用一个函数,让您指定 this
的值以及该函数将接收的任何参数.>
您的第二个示例定义了一个调用 apply
的匿名函数.这是一种常见的模式;bind
提供了一个标准实现,它允许您通过一个简单的函数调用来完成它(因此编写起来更快更容易).
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
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.
call
and apply
will call a function immediately letting you specify both the value of this
and any arguments the function will receive.
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).
这篇关于“调用/应用"和“绑定"有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!