1、什么是this
this和arguments一樣是函數(shù)里自帶的屬性,this的概念如下
官方說法:this引用的是函數(shù)據(jù)以執(zhí)行的環(huán)境對(duì)象
白話文說法1:誰調(diào)用了this所在的函數(shù),this就指向誰
白話文說法2:this所在函數(shù)的執(zhí)行環(huán)境
舉個(gè)栗子:
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里被調(diào)用,所以結(jié)果是window
tiger.eat(); //eat在tiger對(duì)象里被調(diào)用,所以結(jié)果是tiger對(duì)象
結(jié)果截圖:
Image 1.png
1.1、什么是arguments
arguments是函數(shù)里面一個(gè)類似數(shù)組(不是Array的實(shí)例)的對(duì)象,嚴(yán)格來說不是數(shù)組,只是模仿了數(shù)組的特性,一般叫做參數(shù)數(shù)組,里面存儲(chǔ)著所有實(shí)際傳遞過來的參數(shù),傳了多少參數(shù),arguments.length就有多少長。
舉個(gè)栗子:
function func(num1,num2){
console.log(arguments.length);
console.log(arguments[0]);
console.log(arguments[1]);
console.log(arguments[2]);
}
func(); //沒有傳遞實(shí)參,所以長度是0,參數(shù)arguments[0]到[2]都是undefine
func(1,2); // 傳遞了兩個(gè)實(shí)參,所以是2,參數(shù)arguments[0]是1,arguments[1]是2,arguments[2]是undefine
func(1,2,3); //傳遞了三個(gè)實(shí)參,所以是3,arguments[0]是1,arguments[1]是2,arguments[2]是3
結(jié)果截圖:
Image 4.png
2、call函數(shù)的理解和使用
每個(gè)函數(shù)都包含兩個(gè)非繼承而來的方法:apply()和call(),兩個(gè)方法都是在特定的作用域中調(diào)用函數(shù),實(shí)際上等于設(shè)置函數(shù)體內(nèi)this對(duì)象的值,兩個(gè)函數(shù)作用相同,區(qū)別僅在與接收參數(shù)的方式不同,先來講講call()。
舉個(gè)栗子:
var color = 'red';
var o = {color:"blue"};
function sayColor(){
console.log(this.color);
}
sayColor(); //在window環(huán)境中執(zhí)行sayColor函數(shù),所以調(diào)用了window環(huán)境里值為red的color變量
sayColor.call(this); //這里this也是指的window環(huán)境,所以同上面一樣,是在window環(huán)境里執(zhí)行sayColor函數(shù),結(jié)果就一樣是red
sayColor.call(o,'yellow'); //這里在o對(duì)象里執(zhí)行sayColor函數(shù),所以調(diào)用的color是o對(duì)象里的color,結(jié)果為blue
call和applay的區(qū)別:apply是以arguments來傳遞參數(shù),call則是將參數(shù)逐個(gè)列舉出來
舉個(gè)栗子:
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ù)必須一個(gè)一個(gè)傳進(jìn)去
sayColor.call(o,color1,color2);
}
//apply()方法
function func2(color1,color2){
sayColor.apply(this,arguments); //apply函數(shù)的參數(shù)必須是當(dāng)前函數(shù)的arguments
sayColor.apply(o,arguments);
}
console.log('用call函數(shù)產(chǎn)生的結(jié)果')
func1('yellow','black');
console.log('用apply函數(shù)產(chǎn)生的結(jié)果')
func2('yellow','black');
看到差別了吧,兩個(gè)函數(shù)出來的結(jié)果是一樣的:
Image 6.png