what's the difference between 'call/apply' and &
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函数是相同的吗?
bind
返回一个函数,它将像原始函数一样工作,但预定义了this
。当你想要将一个函数传递给事件处理程序或其他异步回调时,通常使用它。
call
和apply
将立即调用一个函数,让您指定this
的值和该函数将接收的任何参数。
第二个示例定义了一个调用apply
的匿名函数。这是一个常见的模式;bind
提供了一个标准的实现,它允许你用一个简单的函数调用来完成它(因此更快更容易编写)。
.call()
-使用指定的参数调用相同的函数
.apply()
-使用数组
.bind()
-创建一个具有相同函数体的新函数,预设值为this
(第一个参数),并返回该函数。
在所有情况下,第一个参数都被用作函数内部this
的值。
区别在于如何进行调用。如果您使用bind
来返回具有绑定this
值的函数,则只需调用该函数:
getx();
如果你没有绑定函数,你想设置this
,你可以设置call
或apply
:
someFunction.call(objectToUseAsThis, arg1, arg2);
// or
someFunction.apply(objectToUseAsThis, [arg1, arg2]);
请注意,如果您有一个绑定函数(如getX
),则在其上使用call
是没有意义的,因为您提供的this
将被绑定的this
覆盖。(使用apply
可能仍然是有用的,如果你有一个数组的值,你想作为参数。)
相关文章:
- Javascript:如何获取函数.apply()的键
- Selenium WebDriver and JavaScript change
- 另一个if(!$scope.$$phase)$scope$apply()szenario-需要帮助才能通关
- call()和apply()实际上是用来欺骗方法处理类似数组的对象的
- PHP and Javascript functions
- Javascript Return and if/else
- SetTimeout and clearTimeout in Javascript
- lightbox in html 5 and javascript
- TimelineJS and AngularJS
- timeago.js with datatable and PHP
- javascript button ajax and php
- Ajax and Json with Rails
- Combine onload, onresize and onclick
- Difference between Array.apply(null, Array(x) ) and Array(x)
- "callback is not the function" and function.apply(
- forEach() and Apply() methods for two dimensional array in J
- Nodejs asyn.apply and Javascript Apply
- 使用js-apply-and-call创建一个webtrend函数来消除重复
- what's the difference between 'call/apply' and &
- 何时以及为什么使用Call and Apply