標籤:nbsp rip 情況 name 方法調用 div blog 函數對象 var
this這個關鍵字在javascript中很常見,也很重要。那麼this到底是指什麼呢?
總結:
1.this代表函數運行時自動產生的一個內部對象,只能在函數內部使用;
2.this始終指向調用函數的那個對象;
下面分四種情況,詳細討論this的用法
一:純粹的函數調用
這是函數的最常用法,屬於全域性調用,這裡this就代表全域對象window
function test(){ this.x = 1; alert(this.x); console.log(this);//Window } test();
而下邊這個案例:
var x = 2; function test(){ this.x = 1; alert(this.x); console.log(this);//Window } test(); console.log(x);//1
就可以證明這裡函數中的this指的是window.
二:作為對象方法的調用
函數還可以作為某個對象的方法調用,這時this就指這個上級對象.
function test(){ console.log(this.x);//1 console.log(this);//o } var o = {}; o.x = 1; o.m = test; o.m();
三:作為建構函式調用
所謂建構函式,就是通過這個函數產生一個新的對象。這時,this就指向這個新對象
function Test(name){ this.name = name; console.log(this);//Test {name: "hehe"} } var t = new Test("hehe");
四:apply調用
apply()是函數對象的一個方法,它的作用是改變函數的調用對象,它的第一個參數就是改變後的調用這個函數的對象。
this這裡值得就是第一個參數的值,若參數為空白,則預設值為全域對象
var x = 0; function test () { console.log(this); console.log(this.x); } var o = {}; o.x = 2; o.m = test; o.m();//this.x-->2 o.m.apply();//this.x-->0 // 結果: // Object {x: 2} // 2 // Window {…} // 0
javascript中的this用法