JS裡面的call, apply以及bind

來源:互聯網
上載者:User

標籤:建立   function   eal   llb   接受   方便   構造   lan   nim   

參考了這篇文章:http://www.tuicool.com/articles/EVF3Eb

給幾個例子

function add(a,b)  {      alert(a+b);  }  function sub(a,b)  {      alert(a-b);  }  add.call(sub,3,1);

這個運行是什麼呢?答案:

4. 啟動並執行是add.因為call是啟動並執行調用者。將第一個參數作為this參數來使用。

 

再來一個例子

function Animal(){        this.name = "Animal";        this.showName = function(){            console.log(this.name);        }    }    function Cat(){        this.name = "Cat";    }    var animal = new Animal();    var cat = new Cat();animal.showName.call(cat,",");   或者animal.showName.apply(cat,[]); 

答案是:

Cat。 因為this換做了Cat。

 

另外,繼承時候用來調用父類的建構函式:

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();

調用完父類之後,cat也有了showName的方法。

 

下面這兩種調用基本等價:

myfunc.call(func,"var"," fun");myfunc.apply(func,["var"," fun"]);

 

而關於bind:作用:改變了內容相關的this

bind與call不同點有兩個:

①bind的傳回值是函數。

//使用bind是 返回改變上下文this後的函數

//使用call是 改變上下文this並執行函數

②後面的參數的使用也有區別

function f(a,b,c){    console.log(a,b,c);}var f_Extend = f.bind(null,"extend_A")f("A","B","C")  //這裡會輸出--> A B Cf_Extend("A","B","C")  //這裡會輸出--> extend_A A Bf_Extend("B","C")  //這裡會輸出--> extend_A B Cf.call(null,"extend_A") //這裡會輸出--> extend_A undefined undefinedcall 是 把第二個及以後的參數作為f方法的實參傳進去而bind 雖說也是擷取第二個及以後的參數用於之後方法的執行,但是f_Extend中傳入的實參則是在bind中傳入參數的基礎上往後排的。

所以,以下兩個是等價的:

var f_Extend = f.bind(null,"extend_A")//↓↓↓var f_Extend = function(b,c){    return f.call(null,"extend_A",b,c);}

有一個應用情境:

例如現在有一個方法 根據不同的檔案類型進行相應的處理,通過bind 就可以建立出簡化版的處理方法function FileDealFunc(type,url,callback){    if(type=="txt"){...}    else if(type=="xml"){...}    .....}var TxtDealFunc = FileDealFunc.bind(this,"txt");//這樣使用的時候更方便一些FileDealFunc("txt",XXURL,func);  //原來TxtDealFunc(XXURL,func); //現在

對於舊的版本,可以用以下方式做相容處理(EcmaScript5中擴充了叫bind的方法(IE6,7,8不支援))

if (!Function.prototype.bind) {    Function.prototype.bind = function(obj) {        var _self = this            ,args = arguments;        return function() {            _self.apply(obj, Array.prototype.slice.call(args, 1));        }    }}

不過上面的函數,好像只接受了一個參數。

 

JS裡面的call, apply以及bind

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.