call和apply

來源:互聯網
上載者:User

標籤:cti   ons   child   new   str   cat   function   傳參   lov   

這兩個在講this的時候就遇到了,它們可以改變函數的上下文this,改變其指向

兩者之間唯一的區別就是傳參的不同

obj.call(thisObject,arg1,arg2....);

obj.apply(thisObject,[arg1,arg2....]);

如果參數已經確定,就可以直接用call就行了,如果參數是動態,那麼用apply比較合適

例子

 1 function cat(){}; 2 cat.prototype={ 3     food:"fish", 4     say:function(){ 5         alert("I love"+this.food); 6    } 7 } 8 var newCat = new cat(); 9 newCat.say();    // I love fish10 11 var dog = {food:"bone"};12 newCat.say.call(dog);    //I love bone

這邊把newCat中this指向了dog。

 

換個角度想一下,這算不算實現了繼承呢

 

1 var parent=function(){2    this.name="jsc";3    this.age = 25;4 }5 var child={};6 console.log(child);    //{}對象7 8 parent.call(child);9 console.log(child);    //{name:"jsc",age:25}

 

 

判斷變數類型時可以使用

我們在使用typeof判斷變數類型的時候,如果是array,Date等,都返回object,所以就沒法判斷具體是哪一種了

這時候可以使用call

 

例如

1 var array = [];2 3 console.log(typeof array);   //  object4 5 Object.prototype.toString.call(array); //[object,array]

 

call和apply

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.