JavaScript 中 this 的工作原理以及注意事項

edithfang發表於2014-05-16

在JavaScript中,this 的概念比較複雜。除了在物件導向程式設計中,this 還是隨處可用的。這篇文章介紹了this 的工作原理,它會造成什麼樣的問題以及this 的相關例子。 要根據this 所在的位置來理解它,情況大概可以分為3種:

  1. 在函式中:this 通常是一個隱含的引數。

  2. 在函式外(頂級作用域中):在瀏覽器中this 指的是全域性物件;在Node.js中指的是模組(module)的匯出(exports)。

  3. 傳遞到eval()中的字串:如果eval()是被直接呼叫的,this 指的是當前物件;如果eval()是被間接呼叫的,this 就是指全域性物件。

對這幾個分類,我們做了相應的測試:

  1. 在函式中的this函式基本可以代表JS中所有可被呼叫的結構,所以這是也最常見的使用this 的場景,而函式又能被子分為下列三種角色:

    1.1  在實函式中的this

    在實函式中,this 的值是取決於它所處的上下文的模式

  • Sloppy模式:this 指的是全域性物件(在瀏覽器中就是window)。

    function sloppyFunc() {
        console.log(this === window); // true
    }
    sloppyFunc();
  • Strict模式:this 的值是undefined。

    function strictFunc() {
        'use strict';
        console.log(this === undefined); // true
    }
    strictFunc();

    this 是函式的隱含引數,所以它的值總是相同的。不過你是可以通過使用call()或者apply()的方法顯示地定義好this的值的。

    function func(arg1, arg2) {
        console.log(this); // 1
        console.log(arg1); // 2
        console.log(arg2); // 3
    }
    func.call(1, 2, 3); // (this, arg1, arg2)
    func.apply(1, [2, 3]); // (this, arrayWithArgs)

    1.2  構造器中的this

    你可以通過new 將一個函式當做一個構造器來使用。new 操作建立了一個新的物件,並將這個物件通過this 傳入構造器中。

    var savedThis;
    function Constr() {
        savedThis = this;
    }
    var inst = new Constr();
    console.log(savedThis === inst); // true

    JS中new 操作的實現原理大概如下面的程式碼所示(更準確的實現請看這裡,這個實現也比較複雜一些):

    function newOperator(Constr, arrayWithArgs) {
        var thisValue = Object.create(Constr.prototype);
        Constr.apply(thisValue, arrayWithArgs);
        return thisValue;
    }

    1.3  方法中的this

    在方法中this 的用法更傾向於傳統的面嚮物件語言:this 指向的接收方,也就是包含有這個方法的物件。

    var obj = {
        method: function () {
            console.log(this === obj); // true
        }
    }
    obj.method();
  • 實函式

  • 構造器

  • 方法

  • 作用域中的this在瀏覽器中,作用域就是全域性作用域,this 指的就是這個全域性物件(就像window):

    <script>
        console.log(this === window); // true
    </script>

    在Node.js中,你通常都是在module中執行函式的。因此,頂級作用域是個很特別的模組作用域(module scope):

    // `global` (not `window`) refers to global object:
    console.log(Math === global.Math); // true
     
    // `this` doesn’t refer to the global object:
    console.log(this !== global); // true
    // `this` refers to a module’s exports:
    console.log(this === module.exports); // true
  • eval()中的thiseval()可以被直接(通過呼叫這個函式名&#8217;eval&#8217;)或者間接(通過別的方式呼叫,比如call())地呼叫。要了解更多細節,請看這裡

    // Real functions
    function sloppyFunc() {
        console.log(eval(&#039;this&#039;) === window); // true
    }
    sloppyFunc();
     
    function strictFunc() {
        &#039;use strict&#039;;
        console.log(eval(&#039;this&#039;) === undefined); // true
    }
    strictFunc();
     
    // Constructors
    var savedThis;
    function Constr() {
        savedThis = eval(&#039;this&#039;);
    }
    var inst = new Constr();
    console.log(savedThis === inst); // true
     
    // Methods
    var obj = {
        method: function () {
            console.log(eval(&#039;this&#039;) === obj); // true
        }
    }
    obj.method();
  • this有關的陷阱你要小心下面將介紹的3個和this 有關的陷阱。要注意,在下面的例子中,使用Strict模式(strict mode)都能提高程式碼的安全性。由於在實函式中,this 的值是undefined,當出現問題的時候,你會得到警告。4.1  忘記使用new如果你不是使用new來呼叫構造器,那其實你就是在使用一個實函式。因此this就不會是你預期的值。在Sloppy模式中,this 指向的就是window 而你將會建立全域性變數:

    function Point(x, y) {
        this.x = x;
        this.y = y;
    }
    var p = Point(7, 5); // we forgot new!
    console.log(p === undefined); // true
     
    // Global variables have been created:
    console.log(x); // 7
    console.log(y); // 5

    不過如果使用的是strict模式,那你還是會得到警告(this===undefined):

    function Point(x, y) {
       &#039;use strict&#039;;
        this.x = x;
        this.y = y;
    }
    var p = Point(7, 5);
    // TypeError: Cannot set property &#039;x&#039; of undefined

    4.2 不恰當地使用方法如果你直接取得一個方法的值(不是呼叫它),你就是把這個方法當做函式在用。當你要將一個方法當做一個引數傳入一個函式或者一個呼叫方法中,你很可能會這麼做。setTimeout()和註冊事件控制程式碼(event handlers)就是這種情況。我將會使用callIt()方法來模擬這個場景:

    /** Similar to setTimeout() and setImmediate() */
    function callIt(func) {
        func();
    }

    如果你是在Sloppy模式下將一個方法當做函式來呼叫,*this*指向的就是全域性物件,所以之後建立的都會是全域性的變數。

    var counter = {
        count: 0,
        // Sloppy-mode method
        inc: function () {
            this.count++;
        }
    }
    callIt(counter.inc);
     
    // Didn’t work:
    console.log(counter.count); // 0
     
    // Instead, a global variable has been created
    // (NaN is result of applying ++ to undefined):
    console.log(count);  // NaN

    如果你是在Strict模式下這麼做的話,this是undefined的,你還是得不到想要的結果,不過至少你會得到一句警告:

    var counter = {
        count: 0,
        // Strict-mode method
        inc: function () {
            &#039;use strict&#039;;
            this.count++;
        }
    }
    callIt(counter.inc);
     
    // TypeError: Cannot read property &#039;count&#039; of undefined
    console.log(counter.count);

    要想得到預期的結果,可以使用bind()

    var counter = {
        count: 0,
        inc: function () {
           this.count++;
        }
    }
    callIt(counter.inc.bind(counter));
    // It worked!
    console.log(counter.count); // 1

    bind()又建立了一個總是能將this的值設定為counter 的函式。

    4.3 隱藏this當你在方法中使用函式的時候,常常會忽略了函式是有自己的this 的。這個this 又有別於方法,因此你不能把這兩個this 混在一起使用。具體的請看下面這段程式碼:

    var obj = {
        name: &#039;Jane&#039;,
        friends: [ &#039;Tarzan&#039;, &#039;Cheeta&#039; ],
        loop: function () {
            &#039;use strict&#039;;
            this.friends.forEach(
                function (friend) {
                    console.log(this.name+&#039; knows &#039;+friend);
                }
            );
        }
    };
    obj.loop();
    // TypeError: Cannot read property &#039;name&#039; of undefined

    上面的例子裡函式中的this.name 不能使用,因為函式的this 的值是undefined,這和方法loop()中的this 不一樣。下面提供了三種思路來解決這個問題:

    • that=this,將this 賦值到一個變數上,這樣就把this 顯性地表現出來了(除了thatself 也是個很常見的用於存放this的變數名),之後就使用那個變數:

      loop: function () {
          &#039;use strict&#039;;
          var that = this;
          this.friends.forEach(function (friend) {
              console.log(that.name+&#039; knows &#039;+friend);
          });
      }
    • bind()。使用bind()來建立一個函式,這個函式的this 總是存有你想要傳遞的值(下面這個例子中,方法的this):

      loop: function () {
          &#039;use strict&#039;;
          this.friends.forEach(function (friend) {
              console.log(this.name+&#039; knows &#039;+friend);
          }.bind(this));
      }
    • 用forEach的第二個引數。forEach的第二個引數會被傳入回撥函式中,作為回撥函式的this 來使用。

      loop: function () {
          &#039;use strict&#039;;
          this.friends.forEach(function (friend) {
              console.log(this.name+&#039; knows &#039;+friend);
          }, this);
      }
  • 最佳實踐

  • 理論上,我認為實函式並沒有屬於自己的this,而上述的解決方案也是按照這個思想的。ECMAScript 6是用箭頭函式(arrow function)來實現這個效果的,箭頭函式就是沒有自己的this 的函式。在這樣的函式中你可以隨便使用this,也不用擔心有沒有隱式的存在。

    loop: function () {
        &#039;use strict&#039;;
        // The parameter of forEach() is an arrow function
        this.friends.forEach(friend => {
            // `this` is loop’s `this`
            console.log(this.name+&#039; knows &#039;+friend);
       });
    }

    我不喜歡有些API把this 當做實函式的一個附加引數:

    beforeEach(function () {  
        this.addMatchers({  
            toBeInRange: function (start, end) {  
                ...
           }  
        });  
    });

    把一個隱性引數寫成顯性地樣子傳入,程式碼會顯得更好理解,而且這樣和箭頭函式的要求也很一致:

    beforeEach(api => {
        api.addMatchers({
            toBeInRange(start, end) {
                ...
            }
        });
    });
    評論(1)

    相關文章