js 中的call apply

bind的使用

obj.bind(thisObj, arg1, arg2, ...);

把obj绑定到thisObj,这时候thisObj具备了obj的属性和方法。与call和apply不同的是,bind绑定后不会立即执行。

同样是add()和sub():

add.bind(sub, 5, 3); //不再返回8
add.bind(sub, 5, 3)(); //8

如果bind的第一个参数是null或者undefined,等于将this绑定到全局对象。


在javascript OOP中,我们经常会这样定义:
function cat(){
}
cat.prototype={
food:"fish",
say: function(){
alert("I love "+this.food);
}
}


var blackCat = new cat;
blackCat.say();

但是如果我们有一个对象whiteDog = {food:"bone"},我们不想对它重新定义say方法,那么我们可以通过call或apply用blackCat的say方法:blackCat.say.call(whiteDog);

所以,可以看出call和apply是为了动态改变this而出现的,当一个object没有某个方法,但是其他的有,我们可以借助call或apply用其它对象的方法来操作。

用的比较多的,通过document.getElementsByTagName选择的dom 节点是一种类似array的array。它不能应用Array下的push,pop等方法。我们可以通过:
var domNodes = Array.prototype.slice.call(document.getElementsByTagName("*"));
这样domNodes就可以应用Array下的所有方法了。

1.call()

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

2.apply()

语法:obj1.call(obj2[,arrArg])
定义:用obj2对象来代替obj1,调用obj1的方法。即将obj1应用到obj2上。
说明:call ()和apply()作用一样,但是call()可以接收任何类型的参数,而apply()只能接收数组参数。

3.基本用法

[javascript] view plain copy
 
  1. function add(a,b){  
  2.     return a+b;  
  3. }  
  4. function sub(c,d){  
  5.     return c-d;  
  6. }  
  7. function result(){  
  8.     this.addValue = null;  
  9.     this.subValue = null;  
  10.     this.showResult=function(){  
  11.         alert(this.addValue);  
  12.         alert(this.subValue);  
  13.     }  
  14. }  
  15. var r = new result();  
  16. r.addValue = add.call(sub,4,2); //6,将add方法应用到sub上,即sub的指针指向add方法  
  17. r.subValue = sub.call(add,4,2); //2,用add对象替换sub对象,并调用sub对象的方法  
  18. r.showResult(); //在js中函数也是一个Function对象,函数名即是对象引用  

4.继承特性

[javascript] view plain copy
 
  1. function add(a,b){  
  2.     return a+b;  
  3. }  
  4. function sub(c,d){  
  5.     return c-d;  
  6. }  
  7. function result(){  
  8.     this.addValue = null;  
  9.     this.subValue = null;  
  10.     this.showResult=function(){  
  11.         alert(this.addValue);  
  12.         alert(this.subValue);  
  13.     }  
  14. }  
  15. var r = new result();  
  16. r.addValue = add.call(r,4,2);   //6,r继承add函数的所有特性  
  17. r.subValue = sub.call(r,4,2);   //2,r集成sub函数的所有特性  
  18. r.showResult();   
  19. "劫持"别人的方法

    此时foo中的logName方法将被bar引用 ,this指向了bar

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    var foo = {
      name:"mingming",
      logName:function(){
        console.log(this.name);
      }
    }
    var bar={
      name:"xiaowang"
    };
    foo.logName.call(bar);//xiaowang

    实现继承

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    function Animal(name){  
      this.name = name;  
      this.showName = function(){  
        console.log(this.name);  
      }  
    }  
     
    function Cat(name){ 
      Animal.call(this, name); 
    }  
     
    var cat = new Cat("Black Cat");  
    cat.showName(); //Black Cat

    在实际开发中,经常会遇到this指向被不经意改变的场景。
    有一个局部的fun方法,fun被作为普通函数调用时,fun内部的this指向了window,但我们往往是想让它指向该#test节点,见如下代码:

    1
    2
    3
    4
    5
    6
    7
    8
    window.id="window";
    document.querySelector('#test').onclick = function(){
      console.log(this.id);//test
      var fun = function(){
        console.log(this.id);
      }
      fun();//window
    }

    使用call,apply我们就可以轻松的解决这种问题了

    1
    2
    3
    4
    5
    6
    7
    8
    window.id="window";
    document.querySelector('#test').onclick = function(){
      console.log(this.id);//test
      var fun = function(){
        console.log(this.id);
      }
      fun.call(this);//test
    }

    当然你也可以这样做,不过在ECMAScript 5strict模式下,这种情况下的this已经被规定为不会指向全局对象,而是undefined:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    window.id="window";
    document.querySelector('#test').onclick = function(){
      var that = this;
      console.log(this.id);//test
      var fun = function(){
        console.log(that.id);
      }
      fun();//test
    }
    1
    2
    3
    4
    5
    function func(){
      "use strict"
      alert ( this );  // 输出:undefined
    }
    func();

    其他用法

    类数组

    这里把符合以下条件的对象称为类数组

    1.具有length属性

    2.按索引方式存储数据

    3.不具有数组的push,pop等方法

    常见类数组有 arguments,NodeList!

    1
    2
    3
    4
    (function(){
      Array.prototype.push.call(arguments,4);
      console.log(arguments);//[1, 2, 3, 4]
    })(1,2,3)

    这样就往arguments中push一个4进去了

    Array.prototype.push 页可以实现两个数组合并

    同样push方法没有提供push一个数组,但是它提供了push(param1,param,…paramN) 所以同样也可以通过apply来装换一下这个数组,即:

    1
    2
    3
    4
    var arr1=new Array("1","2","3");
    var arr2=new Array("4","5","6");
    Array.prototype.push.apply(arr1,arr2);
    console.log(arr1);//["1", "2", "3", "4", "5", "6"]

    也可以这样理解,arr1调用了push方法,参数是通过apply将数组装换为参数列表的集合.

    再比如我想求类数组中的最大值

    1
    2
    3
    4
    (function(){
      var maxNum = Math.max.apply(null,arguments);
      console.log(maxNum);//56
    })(34,2,56);

    判断类型

     
    1
    2
    3
    4
    5
    6
    7
    console.log(Object.prototype.toString.call(123)) //[object Number]
    console.log(Object.prototype.toString.call('123')) //[object String]
    console.log(Object.prototype.toString.call(undefined)) //[object Undefined]
    console.log(Object.prototype.toString.call(true)) //[object Boolean]
    console.log(Object.prototype.toString.call({})) //[object Object]
    console.log(Object.prototype.toString.call([])) //[object Array]
    console.log(Object.prototype.toString.call(function(){})) //[object Function]
原文地址:https://www.cnblogs.com/liangshuang/p/8478109.html