JavaScript 中的 this 關鍵字

    this是Javascript語言的一個關鍵字。它表明函數運行時,自動生成一個內部對象,只能在函數內部使用。this所指的就是直至包含this指針的上層對象。app

   

    普通函數  ---------this-全局對象windowide

    對象的方法---------this-該對象函數

    構造函數  ---------this-新構造的對象this


    經過call和apply能夠從新定義函數的執行環境,即this的指向。隨着函數使用場合的不一樣,this的值會發生變化。可是有一個總的原則,那就是this指的是,調用函數的那個對象。指針


  1. 全局性調用,此時this表明全局對象Global對象

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

2. 做爲對象方法的調用,這時this就指這個上級對象。ip

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

3.做爲構造函數調用,這時,this就指這個新對象。ci

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

4.call,apply調用it

    apply(),call()是函數對象的一個方法,做用是改變函數的調用對象,第一個參數就表示改變後的調用這個函數的對象。所以,this指的就是這第一個參數。io

    

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

  apply()的參數爲空時,默認調用全局對象。所以,這時的運行結果爲0,證實this指的是全局對象。

相關文章
相關標籤/搜索