(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)
相關文章
相關標籤/搜索