“调用/应用"和“绑定"有什么区别 [英] what's the difference between 'call/apply' and '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
bind和call/apply的用法非常相似,我想知道它们之间有什么区别.上面的两个getX函数是相同的吗?
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
返回一个函数,该函数的作用类似于原始函数,但预定义了this
.通常在要将函数传递给事件处理程序或其他异步回调时使用.
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
和apply
将立即调用一个函数,让您同时指定this
的值和该函数将接收的任何参数.
call
and apply
will call a function immediately letting you specify both the value of this
and any arguments the function will receive.
您的第二个示例定义了一个调用apply
的匿名函数.这是一种常见的模式. bind
提供了标准的实现,使您可以通过简单的函数调用(因此更快捷,更容易编写)来做到这一点.
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屋!