通俗易懂的JS this

前言java

在JavaScript中this的指向老是讓人很困惑,它到底指的啥?爲了完全弄清它,咱們就來探討一下吧。this在不一樣的執行環境,不一樣的用法下會有所不一樣,如下分幾種狀況,討論this的指向。node

this指向分類討論

this在全局做用域中瀏覽器

// global scope

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

this.foo = 'def';
alert(foo); // def
複製代碼

在全局做用域/全局環境(global scope| global context)中,this指向的就是全局變量bash

  • 在瀏覽器裏,指向 window 對象
  • 在Node.js裏,指向 global 對象

this在函數(function)裏ide

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的值nomaloop

當咱們建立一個新的對象,bigBoat,它的size屬性爲big,可是bigBoat這個對象沒有boatInfo()方法,因而咱們把boat.boatInfo()的方法賦給了它。而後咱們調用bigBoat.boatInfo(),發現this不等於boat,this.size的值爲bigui

this的指向改變了!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.spa

要理解以上的變化,首先要明白,在任何函數中,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
複製代碼

那個元素觸發事件,this就指向那個元素

總結

以上,對於函數中的this,經過查看()左邊所屬的對象去肯定,真的很好用。

而實質上,this是在建立函數的執行環境時,在建立階段肯定的,所以,弄透執行環境,去思考執行環境建立階段的this的指向,this的指向就不會弄錯了吧。

相關文章
相關標籤/搜索