javascript中this問題

來源:互聯網
上載者:User

一、this的使用方式

1.在html的事件屬性中使用this

  例如:<input type="button" id="button2" value="button222" onclick="javascript:alert(this.id);" />

2.在事件處理函數中使用this

例如:button2.onclick = function(){
alert(this.name);
}

3.如果在全域函數中使用,則this為window對象

例如:alert(this == window);  //true

4.在建構函式中使用this

例如: function  People(name,age){

            this.name = name;

            this.age =  age;

         }

5.在原型模式中使用this

 例如:

function  People(name,age){

            this.name = name;

            this.age =  age;

         }

  Peopel.prototype.getName = function(){

       return this.name;

  }

6.css運算式中使用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心得 

    其實那個對象調用this所在的對象,那麼this就指向當前的對象(注意此時this不位於嵌套閉包函數中);如果直接執行this所在的函數,那麼this指向window對象。

    特殊案例:    

function a() {    alert(this);}a.call(null);關於 a.call(null);  根據ECMAScript262規範規定:如果第一個參數傳入的對象調用者是null或者undefined的話,call方法將把全域對象(也就是window)作為this的值。所以,不管你什麼時候傳入null,其this都是全域對象window。

  

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.