解析javascript關鍵字this

  • 2019 年 12 月 4 日
  • 筆記

本文作者:IMWeb json 原文出處:IMWeb社區 未經同意,禁止轉載

this是javascript語言的一個關鍵字。它可以是全局對象、當前對象或者任意對象,這完全取決於函數的調用方式。下面我們將按照調用方式的不同,分別討論 this 的含義。

作為普通函數調用

    function test() {              this.x = 1;              alert(this.x);        }        test(); // 1

對於這個函數, this關鍵字指向誰呢?我們知道定義在全局的函數, 函數的所有者就是當前頁面, 也就是window對象.因此我們可用通過函數名直接調用, 也可用通過window.方法名來調用, 這個時候, 方法中的this關鍵字指向它的所有者:window對象.

查看window對象的test屬性:

    function test() {              this.x = 1;              alert(this.x);        }        console.log(window.test);    /*      結果:      function test() {              this.x = 1;              alert(this.x);        }  */

事件處理函數

在事件處理函數中this的指向,經常讓我們疑惑,下面來看看

如下:點擊輸入框,顯示輸入框的內容

    // html      <input id="name" type="text"   value="test" />        //js      function test() {           alert(this.value);      }      document.getElementById('name').onclick = test;

以上程式碼可以正確獲取到輸入框的值,但有個問題,這裡的test函數是定義在全局作用域下的,this應該是指向window才對,為什麼可以成功獲取dom的值呢?

問題出在onclick事件綁定的時候,在對onclick綁定處理器的時候, 其實是對id為name的輸入框Dom對象的onclick屬性賦值.

    function test () {          alert(this.value);          }            document.getElementById('name').onclick = test ;          alert(document.getElementById('name').onclick);          /**          * 輸出          * function test () {          * alert(this.value);      * }  */

由以上可知,當事件觸發的時候, 就會去調用Dom對象的onclick方法,此時this指向輸入框。

如果事件寫在html里呢?

    function test() {           alert(this.value);      }        <input id="name" type="text"  value="test"  onclick="test()"/>

此時是獲取不到輸入框的值的,因為此時不是給onclick賦值,而是引用

    //  輸出dom的onclick      alert(document.getElementById('name').onclick);

所以這裡的this指向全局對象window.

作為對象方法的調用

函數還可以作為某個對象的方法調用,這時this就指這個上級對象。

    function test(){      alert(this.x);    }    var object = {};    object.x = 1;    object.m = test;    object.m(); // 1

作為構造函數調用

通過構造函數可以生成一個新對象,this就指向這個新對象。

    function test(){      this.x = 1;    }      var object = new test();    alert(object.x);  // 1

改變this的指向——apply調用

apply()是函數對象的一個方法,它的作用是改變函數的調用對象,切換函數執行的上下文環境(context),即 this 綁定的對象

var object = {       name : 'hello world',       age  : 26  };    function test() {       alert(this.name);  }    test.call(object);  //  hello world