Javascript-call和apply

apply、call

JavaScript中的每個Function對象都有一個apply()方法和一個call()方法,
它們的語法分別爲:數組

/*apply()方法 第一個參數是this指向的對象 第二個參數必須是數組 */
function.apply( thisObj , [argArray] );
/*call()方法  第一個參數是this指向的對象 第二個參數是列舉全部的參數 */
function.call(thisObj,arg1 , arg2, ...argN);

我的理解:A.call(B,...N) 執行A方法但this指向B,而且調用後面的N參數
(將一個函數的對象上下文從初始的上下文改變爲由thisObj指定的新對象,換句話說,就是爲了改變函數體內部 this 的指向
做用:借用另一個對象的方法,而不用拷貝。app

基本用法:

window.firstName = "Cynthia"; 
    window.lastName = "_xie";

    var myObject = {firstName:'my', lastName:'Object'};

    function getName(){
        console.log(this.firstName + this.lastName);
    }

    function getMessage(sex,age){
        console.log(this.firstName + this.lastName + " 性別: " + sex + " age: " + age );
    }

    getName.call(window); // Cynthia_xie
    getName.call(myObject); // myObject

    getName.apply(window); // Cynthia_xie
    getName.apply(myObject);// myObject

    getMessage.call(window,"女",21); //Cynthia_xie 性別: 女 age: 21
    getMessage.apply(window,["女",21]); // Cynthia_xie 性別: 女 age: 21

    getMessage.call(myObject,"未知",22); //myObject 性別: 未知 age: 22
    getMessage.apply(myObject,["未知",22]); // myObject 性別: 未知 age: 22

實現繼承:

function Animal(name){
  this.name = name;
  this.showName = function(){
        alert(this.name);    
    }    
}

function Cat(name){
  //執行animal方法且指向當前的this對象
  Animal.apply(this,[name]);    
}

var cat = new Cat("咕咕");
cat.showName();

/*call的用法*/
Animal.call(this,name);

多重繼承

function Class10(){
      this.showSub = function(a,b){
            alert(a - b);
        }   
    }
    
    function Class11(){
      this.showAdd = function(a,b){
            alert(a + b);
        }  
    }
    
    function Class12(){
      Class10.apply(this);
      Class11.apply(this);   
      // Class10.call(this);
      //Class11.call(this);  
    }
    
    var c2 = new Class12();
    c2.showSub(3,1);    //2
    c2.showAdd(3,1);    //4

apply和call的一些其餘巧妙用法

(1)Math.max 能夠實現獲得數組中最大的一項:函數

由於Math.max不支持Math.max([param1,param2])也就是數組,可是它支持Math.max(param1,param2...),因此能夠根據apply的特色來解決
var max=Math.max.apply(null,array),
這樣就輕易的能夠獲得一個數組中的最大項(apply會將一個數組轉換爲一個參數接一個參數的方式傳遞給方法)。
這塊在調用的時候第一個參數給了null,這是由於沒有對象去調用這個方法,我只須要用這個方法幫我運算,獲得返回的結果就行,因此直接傳遞了一個null過去。用這種方法也能夠實現獲得數組中的最小項:Math.min.apply(null,array)this

(2)Array.prototype.push能夠實現兩個數組的合併prototype

一樣push方法沒有提供push一個數組,
可是它提供了push(param1,param2...paramN),
一樣也能夠用apply來轉換一下這個數組,即:code

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

//獲得合併後數組的長度,由於push就是返回一個數組的長度
也能夠這樣理解,arr1調用了push方法,參數是經過apply將數組轉換爲參數列表的集合
一般在什麼狀況下,可使用apply相似Math.max等之類的特殊用法:
通常在目標函數只須要n個參數列表,而不接收一個數組的形式,
能夠經過apply的方式巧妙地解決這個問題。對象

相關文章
相關標籤/搜索