javascript 中this 的用法

1.<div οnclick="// 可以在里面使用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中类定义有些相似,没有什么太特别的地方。

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/diligentcat/archive/2010/04/23/5518271.aspx

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值