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


 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指向window
fn.call(undefined);        //this指向window
function fn1(name,age){
    console.log(this,name,age);        
}
fn1.call(1,'kaivon',18);        //Number "kaivon" 18
fn1.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']); //如果對應的參數沒寫的話,那就是undefined fn.apply(1,'kaivon',18); //函數里的參數如果不放在數組中,就會報錯 */

 

 

 

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM