(JavaScript) this的用法

1、全局范围

this // window

全局范围中的this将会指向全局对象,即windowjavascript

2、普通函数调用

function foo(x) {
  this.x = x;
}
foo(3);
(x /* or this.x */); // 3

this指向全局对象,即window。严格模式时,为undefinedhtml

3、做为对象的方法调用

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

4、做为构造函数

var foo = new Bar(name) {
  this.name = name;
  this.age = 28;
}

函数内部的this指向建立的对象。闭包

5、闭包(内部函数)

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.namefoo,因此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

6、使用call与apply设置this

fun.apply(thisArg, [argsArray])
fun.call(thisArg[, arg1[, arg2[, ...]]])

函数绑定到thisArg这个对象上使用,this就指向thisArg函数

7、总结

  1. 当函数做为对象的方法调用时,this指向该对象。this

  2. 当函数做为淡出函数调用时,this指向全局对象(严格模式时,为undefined)。指针

  3. 构造函数中的this指向新建立的对象。code

  4. 嵌套函数中的this不会继承上层函数的this,若是须要,能够用一个变量保存上层函数的thishtm

一句话总结:若是在函数中使用了this,只有在该函数直接被某对象调用时,该this才指向该对象。

8、一个常见的坑

事件绑定中回调函数的this

addEventListener(elem, func, false);

若是func中有使用thisthis指向elem,即便func的形式是obj.func,其中的this依然指向elem,可用var self = this;的方法解决这个问题。

参考:谈谈Javascript的this指针 (做者:Aaron)
相关文章
相关标签/搜索