JavaScript中with、this用法

來源:互聯網
上載者:User

35

JavaScript中with、this用法小結

with 語句 為一個或一組語句指定預設對象。
用法:with (<對象>) <語句>;
with 語句通常用來縮短特定情形下必須寫的代碼量。在下面的例子中,請注意 Math 的重複使用:
x = Math.cos(3 * Math.PI) + Math.sin(Math.LN10);
y = Math.tan(14 * Math.E);
當使用 with 語句時,代碼變得更短且更易讀:
with (Math) {
   x = cos(3 * PI) + sin(LN10);
   y = tan(14 * E);
}
this 對象 返回“當前”對象。在不同的地方,this 代表不同的對象。如果在 JavaScript 的“主程式”中(不在任何 function 中,不在任何事件處理常式中)使用 this,它就代表 window 對象;如果在 with 語句塊中使用 this,它就代表 with 所指定的對象;如果在事件處理常式中使用 this,它就代表發生事件的對象。
一個常用的 this 用法:
<script>
...
function check(formObj) {
   ...
}
...
</script>
<body ...>
...
<form ...>
...
<input type="text" ... onchange="check(this.form)">
...
</form>
...
</body>
這個用法常用於立刻檢測表單輸入的有效性。
---------------------------------------------
javascript 中this 的用法:
1.<div onclick="// 可以在裡面使用this">division element</div> this 指向div
2.    <div id="elmtDiv">division element</div>
       <script language="javascript">
        var div = document.getElementById('elmtDiv');
        div.attachEvent('onclick', EventHandler); //attachEvent把div的onclick事件和一個方法綁定
         function EventHandler()
         {
         // 在此使用this
          }
        </script>在此this 指向window對象,若要引用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
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中類定義有些相似,沒有什麼太特別的地方。

#【js+jquery+ajax】

相關文章

聯繫我們

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