天天看點

爆肝3小時,為你講透This指向!

引子

在JavaScript中​

​this​

​​的指向總是讓人很困惑,它到底指的啥?為了徹底弄清它,我們就來探讨一下吧。​

​this​

​​在不同的執行環境,不同的用法下會有所不同,以下分幾種情況,讨論​

​this​

​的指向。

this指向分類讨論

this在全局作用域中

// global scope

foo = 'abc';
alert(foo); // abc

this.foo = 'def';
alert(foo); // def      

在全局作用域/全局環境(global scope| global context)中,​

​this​

​指向的就是全局變量

  • 在浏覽器裡,指向​

    ​window​

    ​對象
  • 在Node.js裡,指向​

    ​global​

    ​對象

this在函數(function)裡

var boat = {
    size: 'normal',
    boatInfo: function() {
        alert(this === boat);
        alert(this.size);
    }
};

boat.boatInfo(); // true, 'normal'

var bigBoat = {
    size: 'big'
};

bigBoat.boatInfo = boat.boatInfo;
bigBoat.boatInfo(); // false, 'big'      

上面這段代碼裡,​

​this​

​​指向誰?可以看到,​

​boat​

​​對象有一個​

​size​

​​屬性,和一個​

​boatInfo()​

​​方法。在​

​boatInfo()​

​​方法裡,alert出​

​this​

​​是否和​

​boat​

​​相等,以及​

​this​

​所指向的size屬性。

當我們去用​

​boat.boatInfo()​

​​時,可以看到,​

​this​

​​和​

​boat​

​​是相等的,​

​this.size​

​​的值就是​

​boat.size​

​的值nomal

當我們建立一個新的對象,​

​bigBoat​

​​,它的​

​size​

​​屬性為big,但是​

​bigBoat​

​​這個對象沒有​

​boatInfo()​

​​方法,于是我們把​

​boat.boatInfo()​

​​的方法賦給了它。然後我們調用​

​bigBoat.boatInfo()​

​​,發現​

​this​

​​不等于​

​boat​

​​,​

​this.size​

​的值為big

​this​

​的指向改變了!

The first thing you must realise is that the value of this inside any function is never static, it is always determined every time you call a function, but before the function actually executes it’s code. The value of this inside a function is actually provided by the parent scope in which the function was called, and more importantly, how the actual function syntax was written.

要了解以上的變化,首先要明白,在任何函數中,​

​this​

​的指向都不是靜态的(static)。它總是在你調用一個函數,但尚未執行函數内部代碼前被指定。(檢視參考連結中的執行環境的文章,這個階段,實際就是初始化變量對象,在初始化變量對象的時候,确定了this的指向)實際上,this是 被調用的函數的父作用域 提供的,更重要的是,我們要看看函數調用時是怎麼寫的。

當一個函數被調用時,應該立馬看​

​()​

​左邊的部分。

  • 如果​

    ​()​

    ​​左邊是一個引用(reference),那麼,函數的​

    ​this​

    ​指向的就是這個引用所屬的對象
  • 否則​

    ​this​

    ​指向的就是全局對象(window|global)
function bar() {
    alert(this);
}
bar(); // global - because the method bar() belongs to the global object when invoked
// 這裡,this指向的是全局對象。我們先看()的左邊,是bar,
// 那麼bar屬于誰呢?bar屬于全局對象,是以this指向的就是全局對象。

var foo = {
    baz: function() {
        alert(this);
    }
}
foo.baz(); // foo - because the method baz() belongs to the object foo when invoked
// 這裡,this指向的是foo,先看()左邊是baz,baz屬于foo,是以baz裡的this指向的就是foo      

如果代碼都那麼簡單,那麼​

​this​

​的指向也就簡單明了了。來點複雜點的看看:

var foo = {
    baz: function() {
        alert(this);
    }
}
foo.baz(); // foo - because baz belongs to the foo object when invoked

var anotherBaz = foo.baz;
anotherBaz(); // global - because the method anotherBaz() belongs to the global object when invoked, NOT foo
// this指向全局對象,()左邊是anotherBaz,屬于全局對象      

可以看到​

​baz()​

​​中​

​this​

​​的指向老是變來變去的。再來看看嵌套在對象裡的​

​this​

​的指向

var anum = 0;

var foo = {
    anum: 10,
    baz: {
        anum: 20,
        bar: function() {
            console.log(this.anum);
        }
    }
}
foo.baz.bar(); // 20 - because left side of () is bar, which belongs to baz object when invoked
// ()左邊是bar,bar屬于foo.baz,是以this就是foo.baz,this.anum = foo.baz.anum = 20

var hello = foo.baz.bar;
hello(); // 0 - because left side of () is hello, which belongs to global object when invoked
// ()左邊是hello,hello屬于全局對象,是以this指向全局對象,this.anum = window.anum = 0      

再來看個例子:

const obj = {
  name: 'spike',
  friends: ['deer', 'cat'],
  loop: function() {
    this.friends.forEach( // 這個this指向obj
      function( friend ) {
        console.log(`${this.name} knows ${friend}`);
        console.log(this === global); // 在node.js環境下,全局對象為global
      }
    )
  }
}

obj.loop();
// ()左邊是loop,屬于obj,是以loop函數中的this指向obj      

輸出

$ node test
undefined knows dear
true
undefined knows cat
true      

可以看到,在forEach中的this并不是期待的那樣指向obj,而是指向全局對象了

可以用上面提到的,還是看​

​()​

​​左邊,在forEach中,​

​()​

​左邊是function,而不是一個引用, 是以this指向的就是全局對象

這裡其實我也有點迷惑,當不明白Scope的結構時候,可以通過在浏覽器中運作代碼,去調試面闆檢視函數執行時的作用域變化。

在構造函數裡的this指向

當使用​

​new​

​​關鍵字去執行構造函數時,構造函數中的​

​this​

​指向的的就是建立的那個對象執行個體。

var savedThis;
    function Constr() {
        // 儲存構造函數中的this
        savedThis = this;
    }
    // 通過new關鍵字執行構造函數
    var inst = new Constr();
    
    // 構造函數中的this指向的就是新建立的對象執行個體inst
    console.log(savedThis === inst); // true      

如果你沒有用​

​new​

​關鍵字去執行構造函數,那麼就要分析函數被調用時所屬的作用域了

function Point(x, y) {
        this.x = x;
        this.y = y;
    }
    var p = Point(7, 5); // 沒有用new關鍵字去執行構造函數!
    
    console.log(p === undefined); // 沒有用new,是以構造函數沒有傳回一個執行個體對象, 是以p === undefined
    
    // 沒有用new關鍵字,Point(7,5);就隻是把函數執行了一遍
    // ()左邊是Point,屬于全局對象,是以this指向全局對象
    console.log(x); // 7
    console.log(y); // 5      

在事件處理器(event handler)中this的指向

<div id="test">I am an element with id #test</div>

function doAlert() { 
    alert(this.innerHTML); 
} 

doAlert(); // undefined 
// doAlert()屬于全局對象

var myElem = document.getElementById('test'); 
myElem.onclick = doAlert; 

alert(myElem.onclick === doAlert); // true 
myElem.onclick(); // I am an element
// ()左邊是onclick也就是doAlert,屬于myElem,是以this指向myElem      
總結

繼續閱讀