1、全局代碼中的this 是指向全局對象,在瀏覽器中是window
alert(this) //window
2、作為單純的函數調用:
function fooCoder(x) { this.x = x; } fooCoder(2); alert(x);// 全局變量x值為2
在普通函數中的this,指向了全局函數,即window ,在嚴格模式下,是undefined
3、作為對象的方法調用:
var name = "clever coder"; var person = { name : "foocoder", hello : function(sth){ console.log(this.name + " says " + sth); } } person.hello("hello world");
輸出 foocoder says hello world。this指向person對象,即當前對象。
4、作為構造函數:
new FooCoder();
函數內部的this指向新創建的對象
5、內部函數
var name = "clever coder"; var person = { name : "foocoder", hello : function(sth){ var sayhello = function(sth) { console.log(this.name + " says " + sth); }; sayhello(sth); } } person.hello("hello world");//clever coder says hello world
在內部函數中,this沒有按預想的綁定到外層函數對象上,而是綁定到了全局對象。這里普遍被認為是JavaScript語言的設計錯誤,因為沒有人想讓內部函數中的this指向全局對象。一般的處理方式是將this作為變量保存下來,一般約定為that或者self:
var name = "clever coder"; var person = { name : "foocoder", hello : function(sth){ var that = this; var sayhello = function(sth) { console.log(that.name + " says " + sth); }; sayhello(sth); } } person.hello("hello world");//foocoder says hello world
6、使用apply和call設置this
person.hello.call(person, "world")
apply和call類似,只是后面的參數是通過一個數組傳入,而不是分開傳入。兩者的方法定義:
call( thisArg [,arg1,arg2,… ] ); // 參數列表,arg1,arg2,... apply(thisArg [,argArray] ); // 參數數組,argArray
兩者都是將某個函數綁定到某個具體對象上使用,自然此時的this會被顯式的設置為第一個參數。
總結this:
1.當函數作為對象的方法調用時,this指向該對象。
2.當函數作為淡出函數調用時,this指向全局對象(嚴格模式時,為undefined)
3.構造函數中的this指向新創建的對象
4.嵌套函數中的this不會繼承上層函數的this,如果需要,可以用一個變量保存上層函數的this。
再總結的簡單點,如果在函數中使用了this,只有在該函數直接被某對象調用時,該this才指向該對象。
- obj.foocoder();
- foocoder.call(obj, ...);
- foocoder.apply(obj, …);
原文地址:http://www.cnblogs.com/aaronjs/archive/2011/09/02/2164009.html#_h1_6