1弹惦、什么是this
this和arguments一樣是函數(shù)里自帶的屬性追逮,this的概念如下
官方說法:this引用的是函數(shù)據(jù)以執(zhí)行的環(huán)境對象
白話文說法1:誰調用了this所在的函數(shù)呛牲,this就指向誰
白話文說法2:this所在函數(shù)的執(zhí)行環(huán)境
舉個栗子:
console.log(this); //window
function func1(){
console.log(this);
}
function animal(){
this.eat = function(){
console.log(this);
}
}
var tiger = new animal();
func1(); //func1函數(shù)在window里被調用鞍恢,所以結果是window
tiger.eat(); //eat在tiger對象里被調用希太,所以結果是tiger對象
結果截圖:
Image 1.png
1.1狼速、什么是arguments
arguments是函數(shù)里面一個類似數(shù)組(不是Array的實例)的對象琅锻,嚴格來說不是數(shù)組,只是模仿了數(shù)組的特性,一般叫做參數(shù)數(shù)組恼蓬,里面存儲著所有實際傳遞過來的參數(shù)惊完,傳了多少參數(shù),arguments.length就有多少長处硬。
舉個栗子:
function func(num1,num2){
console.log(arguments.length);
console.log(arguments[0]);
console.log(arguments[1]);
console.log(arguments[2]);
}
func(); //沒有傳遞實參小槐,所以長度是0,參數(shù)arguments[0]到[2]都是undefine
func(1,2); // 傳遞了兩個實參荷辕,所以是2凿跳,參數(shù)arguments[0]是1,arguments[1]是2疮方,arguments[2]是undefine
func(1,2,3); //傳遞了三個實參控嗜,所以是3,arguments[0]是1骡显,arguments[1]是2疆栏,arguments[2]是3
結果截圖:
Image 4.png
2、call函數(shù)的理解和使用
每個函數(shù)都包含兩個非繼承而來的方法:apply()和call()惫谤,兩個方法都是在特定的作用域中調用函數(shù)壁顶,實際上等于設置函數(shù)體內this對象的值,兩個函數(shù)作用相同石挂,區(qū)別僅在與接收參數(shù)的方式不同博助,先來講講call()。
舉個栗子:
var color = 'red';
var o = {color:"blue"};
function sayColor(){
console.log(this.color);
}
sayColor(); //在window環(huán)境中執(zhí)行sayColor函數(shù)痹愚,所以調用了window環(huán)境里值為red的color變量
sayColor.call(this); //這里this也是指的window環(huán)境富岳,所以同上面一樣,是在window環(huán)境里執(zhí)行sayColor函數(shù)拯腮,結果就一樣是red
sayColor.call(o,'yellow'); //這里在o對象里執(zhí)行sayColor函數(shù)窖式,所以調用的color是o對象里的color,結果為blue
call和applay的區(qū)別:apply是以arguments來傳遞參數(shù)动壤,call則是將參數(shù)逐個列舉出來
舉個栗子:
var color = 'red';
var o = {color:"blue"};
function sayColor(color1,color2){
console.log(this.color);
console.log(color1);
console.log(color2);
}
//call()方法
function func1(color1,color2){
sayColor.call(this,color1,color2); //call函數(shù)的參數(shù)必須一個一個傳進去
sayColor.call(o,color1,color2);
}
//apply()方法
function func2(color1,color2){
sayColor.apply(this,arguments); //apply函數(shù)的參數(shù)必須是當前函數(shù)的arguments
sayColor.apply(o,arguments);
}
console.log('用call函數(shù)產(chǎn)生的結果')
func1('yellow','black');
console.log('用apply函數(shù)產(chǎn)生的結果')
func2('yellow','black');
看到差別了吧萝喘,兩個函數(shù)出來的結果是一樣的:
Image 6.png