what's the difference between 'call/apply' and 'bind' [duplicate]

让人想犯罪 __ 提交于 2020-05-24 08:15:37

问题


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?


回答1:


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




回答2:


.call() - calls the same function with the specified arguments

.apply() - calls the same function with the arguments specified in an array

.bind() - creates a new function with the same function body, with a preset value of this (the first argument) and returns that function.

In all cases, the first argument is used as the value of this inside the function.




回答3:


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:

getx();

If you don't have a bound function, and you want to set this, you do so with 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.)



来源:https://stackoverflow.com/questions/15677738/whats-the-difference-between-call-apply-and-bind

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!