標籤: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指向