this // window
全局範圍中的this
將會指向全局對象,即window
。javascript
function foo(x) { this.x = x; } foo(3); (x /* or this.x */); // 3
this
指向全局對象,即window
。嚴格模式時,爲undefined
。html
var name = "foo"; var person = { name : "bar", hello : function(sth){ console.log(this.name + " says " + sth); } } person.hello("hello"); // bar says hello
this
指向person
對象,即當前對象。java
var foo = new Bar(name) { this.name = name; this.age = 28; }
函數內部的this
指向建立的對象。閉包
var name = "foo"; var person = { name : "bar", hello : function(sth){ var sayhello = function(sth) { console.log(this.name + " says " + sth); }; sayhello(sth) } } person.hello("hello"); // foo says hello
this.name
爲foo
,因此this
指向全局變量,即window
。因此,通常將this
做爲變量保存下來。代碼以下:app
var name = "foo"; var person = { name : "bar", hello : function(sth){ var self = this; var sayhello = function(sth) { console.log(self.name + " says " + sth); }; sayhello(sth) } } person.hello("hello"); // bar says hello
fun.apply(thisArg, [argsArray]) fun.call(thisArg[, arg1[, arg2[, ...]]])
函數綁定到thisArg
這個對象上使用,this
就指向thisArg
。函數
當函數做爲對象的方法調用時,this
指向該對象。this
當函數做爲淡出函數調用時,this
指向全局對象(嚴格模式時,爲undefined
)。指針
構造函數中的this
指向新建立的對象。code
嵌套函數中的this
不會繼承上層函數的this
,若是須要,能夠用一個變量保存上層函數的this
。htm
一句話總結:若是在函數中使用了this
,只有在該函數直接被某對象調用時,該this
才指向該對象。
事件綁定中回調函數的this
。
addEventListener(elem, func, false);
若是func
中有使用this
,this
指向elem
,即便func
的形式是obj.func
,其中的this依然指向elem
,可用var self = this;
的方法解決這個問題。