(JavaScript) this的用法
文章目录
一、全局范围
this // window
全局范围中的this将会指向全局对象,即window。
二、普通函数调用
function foo(x) {
this.x = x;
}
foo(3);
(x /* or this.x */); // 3
this指向全局对象,即window。严格模式时,为undefined。
三、作为对象的方法调用
var name = "foo";
var person = {
name : "bar",
hello : function(sth){
console.log(this.name + " says " + sth);
}
}
person.hello("hello"); // bar says hello
this指向person对象,即当前对象。
四、作为构造函数
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作为变量保存下来。代码如下:
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
六、使用call与apply设置this
fun.apply(thisArg, [argsArray])
fun.call(thisArg[, arg1[, arg2[, ...]]])
函数绑定到thisArg这个对象上使用,this就指向thisArg。
七、总结
当函数作为对象的方法调用时,
this指向该对象。当函数作为淡出函数调用时,
this指向全局对象(严格模式时,为undefined)。构造函数中的
this指向新创建的对象。嵌套函数中的
this不会继承上层函数的this,如果需要,可以用一个变量保存上层函数的this。
一句话总结:如果在函数中使用了this,只有在该函数直接被某对象调用时,该this才指向该对象。
八、一个常见的坑
事件绑定中回调函数的this。
addEventListener(elem, func, false);
如果func中有使用this,this指向elem,即使func的形式是obj.func,其中的this依然指向elem,可用var self = this;的方法解决这个问题。

评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论