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).