call()與apply() 改變this指向

來源:互聯網
上載者:User

標籤:window   this   orm   name   改變   undefined   class   function   數組   

 call

1、作用

調用函數並且改變this的指向

2、文法

函數名.call(thisArg,arg1,arg2...)

3、參數

   thisArg 函數中this指向的值

arg1,arg2... 從call裡的第二個參數開始,都是真正函數裡的參數

4、傳回值

undefined

 

注意:thisArg 的值為null或者undefined的時候,this是指向window

 

fn.call(1);                //this指向數字fn.call(‘kaivon‘);        //this指向字串fn.call(true);            //this指向布爾值fn.call([1,2,3]);         //this指向數組fn.call({});              //this指向對象fn.call(null);            //this指向windowfn.call(undefined);        //this指向window
function fn1(name,age){    console.log(this,name,age);        }fn1.call(1,‘kaivon‘,18);        //Number "kaivon" 18fn1.call({a:10,b:20},‘陳學輝‘,18);  //Object "陳學輝" 18

 

 

apply與call基本類似,唯一不同的是函數裡參數放在數組裡,如果不放在數組裡就會報錯

 

 apply

1、作用

調用函數並且改變this的指向

2、文法

函數名.apply(thisArg,[arg1,arg2...])

3、參數

   thisArg 函數中this指向的值

[arg1,arg2... ] 從call裡的第二個參數開始,都是真正函數裡的參數
    

4、傳回值

undefined

 

注意:thisArg 的值為null或者undefined的時候,this是指向window

 

function fn(name,age){    console.log(this,name,age);}                        fn.apply({a:10,b:20},[‘kaivon‘,18]);    //Object "kaivon" 18
/*fn.apply(1,[‘kaivon‘]); //如果對應的參數沒寫的話,那就是undefinedfn.apply(1,‘kaivon‘,18); //函數裡的參數如果不放在數組中,就會報錯*/

 

 

 

 

 

 

 

 

 

call()與apply() 改變this指向

相關文章

聯繫我們

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