前言:
看文章標題你就知道,這篇文章我只講一個簡單的Javascript的this關鍵字,說它簡單——它又不簡單,因為曾幾何時我也對this關鍵字有些困惑,它也確實會讓不少程序員感到不解——它像是一個身份多變的“指針”,有時僅看代碼都很難分辨出其當前所指向的對象;恰好這兩天我突然想到應該寫篇關於Javascript方面的博客,也算是為以后的公司技術培訓做點兒准備。這篇文章,我可能更傾向於,用代碼來直接的體現我要描述的內容。好的文章不在於它的篇幅長、內容豐富,而在於或者說更重要的是——應該用言簡意賅的內容讓讀者快速、沒有歧義的明白你所要講解的內容;而對於技術文章,代碼往往就是最好的描述。好了,直接切入正題...
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <title></title> 5 <script src="jquery.js" type="text/javascript"></script> 6 </head> 7 <body> 8 <input id="btnTest" type="button" value="Test" /><br /> 9 <input id="btnTest2" type="button" value="Test2" /><br /> 10 <input id="btnFun" type="button" value="Inner Fun" onclick="this.value=new Date().getSeconds();alert(this);" /><br /> 11 <script type="text/javascript"> 12 //#region 全局this對象,即可以通過this訪問到當前頁面中的所有(標簽或jquery等)對象,此this沒有什么實際意義,也很少會這樣使用 13 this.$.trim(); 14 alert(this.btnFun); 15 alert(this.window.location); 16 //#endregion 17 18 $("#btnTest").click(function () { 19 alert(this.value); //此this是btnTest標簽對象,輸出:Test 20 $("#btnTest2").click(function () { 21 alert(this.value); //此this是btnTest2標簽對象,輸出:Test2 22 }); 23 }); 24 </script> 25 26 <script type="text/javascript"> 27 function UserInfo(name, age) { 28 var _mySecret = "Can't tell you!"; 29 this.Name = name; 30 this.Age = age; 31 32 this.GetMySecret = function () { 33 /// <summary>獲取我的秘密</summary> 34 alert(_mySecret); 35 } 36 37 this.IntroduceMySelf = function () { 38 /// <summary>自我介紹</summary> 39 alert("Hello,My Name is:" + this.Name + ", Age is:" + this.Age); 40 } 41 } 42 43 var userObj = new UserInfo("Tom", 23); 44 userObj.GetMySecret(); 45 userObj.IntroduceMySelf(); 46 </script> 47 <br /> 48 </body> 49 </html>
上面的代碼,就是我們常見的this關鍵字的使用,也在其中添加了必要的代碼注釋,以說明其當前所指代的對象。
this關鍵字:可以理解為是對象的指針,其具體所指向(對應)的對象要看其(使用)所處的(上下文)環境。其常見的使用場景,所代表的對象大致可以分為以下兩類:
1.html標簽(元素)對象:即在html標簽綁定的事件(onclick,onmouseover...)中,this關鍵字表示當前標簽的Dom對象,通過this即可完全控制、操縱此html標簽,如:設置其樣式或綁定其它事件等。
2.function(類)對象:首先,你可能會有疑問——為什么叫做function(類)對象?眾所周知,javascript不存在類(class)的概念,但它所具有的特性卻可以比較好的實現"模擬類",如上面的代碼中的:function UserInfo(name, age)方法。在此對象中this關鍵字可以很自然的理解為當前的function(類)對象,其作用和用法跟面向對象編程語言(如:C#)里的this關鍵字很類似,所以,UserInfo這個方法(類),如果轉換為C#代碼,想必你會能更直觀的理解。代碼如下:
1 public class UserInfo 2 { 3 string _mySecret = "Can't tell you!"; 4 5 public string Name { get; set; } 6 public int Age { get; set; } 7 8 public UserInfo(string name, int age) 9 { 10 this.Name = name; 11 this.Age = age; 12 } 13 14 public string GetMySecret() 15 { 16 return _mySecret; 17 } 18 19 public string IntroduceMySelf() 20 { 21 return ("Hello,My Name is:" + this.Name + ", Age is:" + this.Age); 22 } 23 }
本文就到此結束,如果還是有疑問的地方,或文中有“誤人子弟”的描述,希望大家能留言提出!