jquery中的call和apply方法

call方法:
语法:call([thisObj[,arg1[, arg2[, [,.argN]]]]])
定义:调用一个对象的一个方法,以另一个对象替换当前对象。
说明:
call 方法可以用来代替另一个对象调用一个方法。call 方法可将一个函数的对象上下文从初始的上下文改变为由 thisObj 指定的新对象。
如果没有提供 thisObj 参数,那么 Global 对象被用作 thisObj。

apply方法:
语法:apply([thisObj[,argArray]])
定义:应用某一对象的一个方法,用另一个对象替换当前对象。
说明:
如果 argArray 不是一个有效的数组或者不是 arguments 对象,那么将导致一个 TypeError。
如果没有提供 argArray 和 thisObj 任何一个参数,那么 Global 对象将被用作 thisObj, 并且无法被传递任何参数。

  1. <script language="javascript"><!--
  2. /**定义一个animal类*/
  3. function Animal(){
  4. this.name = "Animal";
  5. this.showName = function(){
  6. alert(this.name);
  7. }
  8. }
  9. /**定义一个Cat类*/
  10. function Cat(){
  11. this.name = "Cat";
  12. }
  13. /**创建两个类对象*/
  14. var animal = new Animal();
  15. var cat = new Cat();
  16. //通过call或apply方法,将原本属于Animal对象的showName()方法交给当前对象cat来使用了。
  17. //输入结果为"Cat"
  18. animal.showName.call(cat,",");
  19. //animal.showName.apply(cat,[]);
  20. / --></script>

以上代码无论是采用animal.showName.call或是animal.showName.apply方法,运行的结果都是输出一个"Cat"的字符串。说明showName方法的调用者被换成了cat对象,而不是最初定义它的animal了。这就是call和apply方法的妙用!

如果cat类中没有定义 this.name = "Cat";,那么执行的发放中弹出的将是NaN对象,不会用Animal中的this.name。其中call和apply中的第二个参数是showname中的options参数。

如:

$.tukibox = function(method) {
if (methods[method]) {
return methods[ method ].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || ! method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.tukibox');
}
};

上面的call中,就是调用Array的slice方法,传入两个参数作为slice的参数。apply当然是让当前对象调用methods对象中的指定方法或者是init初始化方法。

原文地址:https://www.cnblogs.com/guifang/p/2792540.html