Javascript :this關鍵字 詳解
由於 Javascript(簡稱:JS)中的 this 理解起來較為複雜,使得很多入門新手和一些進入前端圈子有些年限的工程師們都對其的用法有些模糊。所以今天為大家帶來 Javascript(簡稱:JS) 中 this 的用法詳解。
this 永遠指向
呼叫
包含 自己(this本身) 的
函式
對應的
物件
。
也就是說,包含 this 的函式 只在乎是誰呼叫了它,跟在哪裡進行的函式宣告沒有關係。
下面就來舉個例子說明:
function test(){
var a = 1;
console。log(this。a);
}
test(); //undefined
如果函式在最外層直接執行,預設繫結的物件是 window,因為 test() 是被window物件呼叫的,所以這裡的 this。a 對應的應該是 全域性變數(或者叫window變數) 而不是test函數里的區域性變數,由於 在 window 物件中沒有宣告 變數a,所以輸出 undefined。
下面我們對程式碼進行改造一下:
var a = 2; //window物件下的變數
function test(){
var a = 1;
console。log(this。a);
}
test(); // 列印結果為 2
下面再來分析一個經典的例子:
var name = ‘China’;
var obj = {
name : ‘America’,
show : function() {
console。log(this。name)
}
}
obj。show(); // America
從上述程式碼可以看出,包含 this 的函式是 show(),而show()函式透過物件obj呼叫的,所以 this。name 指向 obj 中的 name(America);
我們再來對程式碼進行改造:
var name = ‘China’;
var obj = {
name : ‘America’,
show : function() {
return function(){
console。log(this。name);
}
}
}
var a = obj。show();
a(); // China
這裡的 obj。show() 返回的是一個匿名函式
function(){
console。log(this。name);
}
然後賦值給 變數a,等價於:
var a = function(){
console。log(this。name);
}
或
function a(){
console。log(this。name);
}
所以 最後執行的 a()== window。a(), 函式a 裡面的 this。name 指向 window。name(‘China’),所以最終輸出 China。
看到這裡,相信大家對 this 已經有個比較清楚的認識了,下面給大家介紹4種 this 常用的場景。
1。 在一般函式方法中使用 this 指代全域性物件
function test(){
this。x = 1;
alert(this。x);
}
test(); // 1
2。 作為物件方法呼叫,this 指代上級物件
function test(){
alert(this。x);
}
var obj = {};
obj。x = 1;
obj。m = test;
obj。m(); // 1
3。 作為建構函式呼叫,this 指向 new 出的物件
function test(){
this。name = ‘China’;
}
var t = new test();
console。log(t。name); //‘China’
4。 apply, call 呼叫
function Animal(){
this。name = ‘animal’;
}
function Cat(){
Animal。call(this);
}
var cat = new Cat();
console。log(cat。name);// ‘animal’
以上便是 this 全部的解答。