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;
的方法解决这个问题。