javascript this 關鍵字的使用方法

來源:互聯網
上載者:User

文法
this
    this.property
經常習慣於通過整個物體,比如那些包含在形式和方法的情況下,向函數中指定的指令碼。

看個this執行個體

<html>
    <head>
      <title> Using this in passing form information</title>
    <script language="JavaScript">
    <!--
    function displayInfo(form){
      var myWin = open("", "","width=450,height=200");
      myWin.document.write("The defaultValue of the text box is: ");

      myWin.document.write(form.myText.defaultValue);

      myWin.document.write("<br>The name of the text area is: ");

      myWin.document.write(form.myTextArea.name);

      myWin.document.write("<br>The value of the button is: ");

      myWin.document.write(form.myButton.value);

      myWin.document.close();
    }
    -->
    </script>
    </head>
    <body>
    <form name="myForm">
      <textarea name="myTextArea" rows=2 cols=50>
      Here is some text in my text area.
      </textarea>
      <br>
      <input type=TEXT value="Change Me?" name="myText">
      <br>
      <input type=BUTTON value="Display Information" name="myButton" onClick='displayInfo(this.form)'>
    </form>
    </body>
    </html>

下面就來看看,在JavaScript中各種this的使用方法有什麼混亂之處?

    1、在HTML元素事件屬性中inline方式使用this關鍵字:  <div onclick="
 // 可以在裡面使用this

 ">division element</div>

    我們一般比較常用的方法是在此使用:javascirpt: EventHandler(this),這樣的形式。不過這裡其實可以寫任何合法的JavaScript語句,要是高興在此定義個類也可以(不過將會是個內部類)。這裡的原理是指令碼引擎產生了一個div執行個體對象的匿名成員方法,而onclick指向這個方法。

    2、用DOM方式在事件處理函數中使用this關鍵字:

 <div id="elmtDiv">division element</div>
 <script language="網頁特效">
 var div = document.getElementById('elmtDiv');
 div.attachEvent('onclick', EventHandler);

 function EventHandler()
 {
    // 在此使用this
 }
 </script>

    這時的EventHandler()方法中的this關鍵字,指示的對象是IE的window對象。這是因為EventHandler只是一個普通的函數,對於attachEvent後,指令碼引擎對它的調用和div對象本身沒有任何的關係。同時你可以再看看EventHandler的caller屬性,它是等於null的。如果我們要在這個方法中獲得div對象引用,應該使用:this.event.srcElement。

    3、用DHTML方式在事件處理函數中使用this關鍵字:

 <div id="elmtDiv">division element</div>
 <script language="javascript">
 var div = document.getElementById('elmtDiv');
 div.onclick = function()
 {
    // 在此使用this
 };
 </script>

    這裡的this關鍵字指示的內容是div元素對象執行個體,在指令碼中使用DHTML方式直接為div.onclick賦值一個EventHandler的方法,等於為div對象執行個體添加一個成員方法。這種方式和第一種方法的區別是,第一種方法是使用HTML方式,而這裡是DHTML方式,後者指令碼解析引擎不會再產生匿名方法。

    4、類定義中使用this關鍵字:

  function JSClass()
  {
      var myName = 'jsclass';
      this.m_Name = 'JSClass';
  }

  JSClass.prototype.ToString = function()
  {
      alert(myName + ', ' + this.m_Name);
  };

  var jc = new JSClass();
  jc.ToString();

   

這是JavaScript類比類定義中對this的使用,這個和其它的OO語言中的情況非常的相識。但是這裡要求成員屬性和方法必須使用this關鍵字來引用,運行上面的程式會被告知myName未定義。

 

    5、為指令碼引擎內部對象添加原形方法中的this關鍵字:

 

Function.prototype.GetName = function()
  {
      var fnName = this.toString();
      fnName = fnName.substr(0, fnName.indexOf('('));
      fnName = fnName.replace(/^function/, '');
      return fnName.replace(/(^s+)|(s+$)/g, '');
  }
  function foo(){}
  alert(foo.GetName());   

    這裡的this指代的是被添加原形的類的執行個體,和4中類定義有些相似,沒有什麼太特別的地方。

    6、結合2&4,說一個比較迷惑的this關鍵字使用:

  function JSClass()
  {
      this.m_Text = 'division element';
      this.m_Element = document.createElement('DIV');
      this.m_Element.innerHTML = this.m_Text;
       
      this.m_Element.attachEvent('onclick', this.ToString);
  }
  
  JSClass.prototype.Render = function()
  {
      document.body.appendChild(this.m_Element);
  }    

  JSClass.prototype.ToString = function()
  {
      alert(this.m_Text);
  };

  var jc = new JSClass();
  jc.Render();
  jc.ToString();

   

我就說說結果,頁面運行後會顯示:"division element",確定後點擊文字"division element",將會顯示:"undefined"。

    7、CSS的expression運算式中使用this關鍵字:

 

<table width="100" height="100">
      <tr>
          <td>
              <div style="width: expression(this.parentElement.width);
                    height: expression(this.parentElement.height);">
                  division element</div>
          </td>
      </tr>
  </table>

    這裡的this看作和1中的一樣就可以了,它也是指代div元素對象執行個體本身。

    8、函數中的內建函式中使用this關鍵字:

 

function OuterFoo()
  {
      this.Name = 'Outer Name';
 
      function InnerFoo()
      {
          var Name = 'Inner Name';
          alert(Name + ', ' + this.Name);
      }
      return InnerFoo;
  }
  OuterFoo()();

   

運行結果顯示是:"Inner Name, Outer Name"。按我們在2中的講解,這裡的結果如果是"Inner Name, undefined"似乎更合理些吧?但是正確的結果確實是前者,這是由於JavaScript變數範圍的問題決定的

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.