Javascript的關鍵字this詳解

來源:互聯網
上載者:User

在javascript中關鍵字this是一個很難掌握的概念。它在不同的情況下指代不同的對象。下面就來看看,在JavaScript中各種this的使用方法有什麼不同之處?

1、在HTML元素事件屬性中inline方式使用this關鍵字:

<div onclick="method(this)">element</div>

 

這裡的this代表觸發onclick時間的Dom對象。

 

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

1 <div id="elmtDiv">element</div>
2  <script language="javascript">
3  var div = document.getElementById('elmtDiv');
4  div.onclick = function()
5  {
6     // 在此使用this
7  };
8  </script>

 

這裡this指代的對象和上面一樣。

 

3、函數中的this

函數中的this代表調用函數的對象。

1 function print(message)
2 {
3      this.alert(message);
4 }

6 print("this is window");

 

例如上面這個函數print的定義也可以寫成。window.print = function(){}.調用print(),實際上是調用window對象上的方法print。所以print中的this代表window對象。還有類似的情況是在建構函式中定義的方法:

 1 function MyClass(name)
 2 {
 3     this.name = name;
 4     this.toString = function(){
 5         return this.name;
 6     }
 7 }
 8 
 9 var my = new MyClass('myclass');
10 alert(my.toString());

 

this指向的是調用此方法的對象my。

 

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未定義。有關建構函式的相關內容:Javascript(js)使用function定義建構函式有詳細的介紹。

 

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

1 Function.prototype.GetName = function()
2 {
3     var fnName = this.toString(); 
4     fnName = fnName.substr(0, fnName.indexOf('(')); 
5     fnName = fnName.replace(/^function/, ''); 
6     return fnName.replace(/(^\s+)|(\s+$)/g, '');
7 }
8 function foo(){}
9 alert(foo.GetName());    

這裡的this指代的是被添加原形的類的執行個體。

 

6、函數調用中的this

在將函數作為一個對象的方法調用時,如:

1 function print()
2 {
3     alert(this.toString());
4 }

6 print.apply('this is first argument');
7 print.call('this is first argument');

 

在Function.apply和Function.call中的第一個參數就是函數中this的對象。

 

相關文章:Javascript對象原型prototype和繼承

相關文章

聯繫我們

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