javascript 中this 的用法:
1.<div onclick="// 可以在里面使用this">division element</div> this 指向div
2.    <div >
        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 >
 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中类定义有些相似,没有什么太特别的地方。

相关文章:

  • 2021-12-04
  • 2021-12-04
  • 2021-12-06
  • 2021-09-02
猜你喜欢
  • 2021-08-29
  • 2022-12-23
  • 2021-12-04
  • 2021-12-15
相关资源
相似解决方案