`
jayfans3
  • 浏览: 3515 次
  • 性别: Icon_minigender_2
  • 来自: 天津
最近访客 更多访客>>
文章分类
社区版块
存档分类
最新评论
阅读更多
在面向对象编程语言中,对于this关键字我们是非常熟悉的。比如C++、C#和Java等都提供了这个关键字,虽然在开始学习的时候觉得比较难,但只要理解了,用起来是非常方便和意义确定的。JavaScript也提供了这个this关键字,不过用起来就比经典OO语言中要"混乱"的多了。

  下面就来看看,在JavaScript中各种this的使用方法有什么混乱之处?

  1、在HTML元素事件属性中inline方式使用this关键字:
<div onclick="  
// 可以在里面使用this  
 
">division element</div> 
<div onclick="
// 可以在里面使用this

">division element</div>
  我们一般比较常用的方法是在此使用:javascirpt: EventHandler(this),这样的形式。不过这里其实可以写任何合法的JavaScript语句,要是高兴在此定义个类也可以(不过将会是个内部类)。这里的原理是脚本引擎生成了一个div实例对象的匿名成员方法,而onclick指向这个方法。

  2、用DOM方式在事件处理函数中使用this关键字:
<div id="elmtDiv">division element</div>  
<mce:script language="javascript"><!--  
var div = document.getElementById('elmtDiv');  
div.attachEvent('onclick', EventHandler);  
 
function EventHandler()  
{  
  // 在此使用this  
}  
   
// --></mce:script> 
<div id="elmtDiv">division element</div>
<mce:script language="javascript"><!--
var div = document.getElementById('elmtDiv');
div.attachEvent('onclick', EventHandler);

function EventHandler()
{
  // 在此使用this
}

// --></mce:script>
  这时的EventHandler()方法中的this关键字,指示的对象是IE的window对象。这是因为EventHandler只是一个普通的函数,对于attachEvent后,脚本引擎对它的调用和div对象本身没有任何的关系。同时你可以再看看EventHandler的caller属性,它是等于null的。如果我们要在这个方法中获得div对象引用,应该使用:this.event.srcElement。

  3、用DHTML方式在事件处理函数中使用this关键字:
<div id="elmtDiv">division element</div>  
lt;mce:script language="javascript"><!--  
var div = document.getElementById('elmtDiv');  
div.onclick = function()  
{  
// 在此使用this  
};  
 
/ --></mce:script> 
<div id="elmtDiv">division element</div>
<mce:script language="javascript"><!--
var div = document.getElementById('elmtDiv');
div.onclick = function()
{
  // 在此使用this
};

// --></mce:script>
  这里的this关键字指示的内容是div元素对象实例,在脚本中使用DHTML方式直接为div.onclick赋值一个EventHandler的方法,等于为div对象实例添加一个成员方法。这种方式和第一种方法的区别是,第一种方法是使用HTML方式,而这里是DHTML方式,后者脚本解析引擎不会再生成匿名方法。

  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(); 
  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());   
  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中类定义有些相似,没有什么太特别的地方。

  6、结合2&4,说一个比较迷惑的this关键字使用:
view plaincopy to clipboardprint?
function JSClass()  
{  
this.m_Text = 'division element';  
this.m_Element = document.createElement('DIV');  
this.m_Element.innerHTML = this.m_Text;  
   
this.m_Element.attachEvent('onclick', this.ToString);  
}  
   
JSClass.prototype.Render = function()  
{  
document.body.appendChild(this.m_Element);  
}    
 
JSClass.prototype.ToString = function()  
{  
alert(this.m_Text);  
};  
 
var jc = new JSClass();  
jc.Render();   
jc.ToString(); 
  function JSClass()
  {
  this.m_Text = 'division element';
  this.m_Element = document.createElement('DIV');
  this.m_Element.innerHTML = this.m_Text;
  
  this.m_Element.attachEvent('onclick', this.ToString);
  }
  
  JSClass.prototype.Render = function()
  {
  document.body.appendChild(this.m_Element);
  } 

  JSClass.prototype.ToString = function()
  {
  alert(this.m_Text);
  };

  var jc = new JSClass();
  jc.Render();
  jc.ToString();
  我就说说结果,页面运行后会显示:"division element",确定后点击文字"division element",将会显示:"undefined"。

  7、CSS的expression表达式中使用this关键字:
  <table width="100" height="100">  
<tr>  
<td>  
<div style="width: expression(this.parentElement.width);   
  height: expression(this.parentElement.height);">  
  division element</div>  
</td>  
</tr>  
</table> 
  <table width="100" height="100">
<tr>
<td>
<div style="width: expression(this.parentElement.width);
  height: expression(this.parentElement.height);">
  division element</div>
</td>
</tr>
</table>


  这里的this看作和1中的一样就可以了,它也是指代div元素对象实例本身。

  8、函数中的内部函数中使用this关键字:
view plaincopy to clipboardprint?
function OuterFoo()  
{  
this.Name = 'Outer Name';  
 
function InnerFoo()  
{  
var Name = 'Inner Name';   
alert(Name + ', ' + this.Name);  
}  
return InnerFoo;  
}  
OuterFoo()(); 
  function OuterFoo()
  {
  this.Name = 'Outer Name';

  function InnerFoo()
  {
  var Name = 'Inner Name';
  alert(Name + ', ' + this.Name);
  }
  return InnerFoo;
  }
  OuterFoo()();
  运行结果显示是:"Inner Name, Outer Name"。按我们在2中的讲解,这里的结果如果是"Inner Name, undefined"似乎更合理些吧?但是正确的结果确实是前者,这是由于JavaScript变量作用域的问题决定的,详细了解推荐参看"原来JScript中的关键字'var'还是有文章的"一文及回复。

    归纳起来,JavaScript中的this用法有以下3种(详细用法参原文):
    1.在HTML元素事件属性 或 CSS的expression表达式 中inline方式使用this关键字——对应原文的1、7
    2.在事件处理函数中使用this关键字——对应原文的2、3
      其中可分为两种方式
      (1)DOM方式——此种方式的结果是this指向窗口(window)对象
      (2)DHTML方式——此种方式的结果是this指向div元素对象实例
    3.在类定义中使用this关键字并在其 内部函数 或 成员函数(主要是prototype产生)中使用——对应原文的4、5、8
      需要说明的是,在函数也是个对象,因此需要区分 变量定义 和 成员变量定义,如下:
view plaincopy to clipboardprint?
var variableName;        //变量定义  
//作用域:函数定义范围内  
//使用方法:直接使用variableName  
this.varName;            //成员变量定义  
//作用域:函数对象定义范围内及其成员函数中  
//使用方法:this.varName 
var variableName;        //变量定义
//作用域:函数定义范围内
//使用方法:直接使用variableName
this.varName;            //成员变量定义
//作用域:函数对象定义范围内及其成员函数中
//使用方法:this.varName

以上归纳出的三类this的使用方法中,第一种比较容易理解,这里对原文中第6点提到的程序进行了测试和改进如下,以说明上述后两种使用方法:

view plaincopy to clipboardprint?
<html>  
<head>  
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>  
<title>Test "this"</title>  
<mce:script type="text/javascript"><!--  
        function JSClass()  
        {  
            var varText = "func variable!";                                 //函数中的普通变量  
            this.m_Text = 'func member!';                                       //函数类的成员变量  
            this.m_Element = document.createElement('DIV');     //成员变量,创建一个div对象  
            this.m_Element.innerHTML = varText;                         //使用函数的普通变量  
            this.m_Element.attachEvent('onclick', this.ToString);   //给这个对象的事件连上处理函数  
            this.newElement = document.createElement('DIV');  
            this.newElement.innerHTML = "new element";    
            this.newElement.m_Text = "new element text!";           //给创建的对象建个成员  
            this.newElement.onclick = function()  
            {  
                alert(this.m_Text);                                             //指向div对象的成员  
            };  
        }  
     
        JSClass.prototype.Render = function()  
        {  
            document.body.appendChild(this.m_Element);              //把div对象挂在窗口上  
            document.body.appendChild(this.newElement);  
        }       
 
        JSClass.prototype.ToString = function()  
        {  
            alert(this.m_Text);                                                 //指向窗口(window)对象  
        };  
 
        function initialize(){  
            var jc = new JSClass();  
            jc.Render();   
            jc.ToString();                                                          //里面的this指向JSClass类的实例,里面有m_Text成员  
        }  
      
// --></mce:script>  
</head>  
<body>  
<mce:script type="text/javascript"><!--  
        initialize();  
      
// --></mce:script>  
</body>  
</html> 
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Test "this"</title>
<mce:script type="text/javascript"><!--
  function JSClass()
    {
     var varText = "func variable!";         //函数中的普通变量
       this.m_Text = 'func member!';          //函数类的成员变量
        this.m_Element = document.createElement('DIV');  //成员变量,创建一个div对象
        this.m_Element.innerHTML = varText;        //使用函数的普通变量
        this.m_Element.attachEvent('onclick', this.ToString); //给这个对象的事件连上处理函数
        this.newElement = document.createElement('DIV');
        this.newElement.innerHTML = "new element"; 
        this.newElement.m_Text = "new element text!";   //给创建的对象建个成员
        this.newElement.onclick = function()
     {
         alert(this.m_Text);            //指向div对象的成员
     };
    }
  
    JSClass.prototype.Render = function()
    {
        document.body.appendChild(this.m_Element);    //把div对象挂在窗口上
        document.body.appendChild(this.newElement);
    }    

    JSClass.prototype.ToString = function()
    {
        alert(this.m_Text);             //指向窗口(window)对象
    };

  function initialize(){
     var jc = new JSClass();
     jc.Render();
     jc.ToString();               //里面的this指向JSClass类的实例,里面有m_Text成员
    }
   
// --></mce:script>
</head>
<body>
<mce:script type="text/javascript"><!--
     initialize();
   
// --></mce:script>
</body>
</html>

上面的代码执行结果是:
页面加载时,弹出对话框,输出func member!
页面上显示
  func variable!
  new element
单击func variable时,弹出对话框,显示undefined
  ——因为这时toString函数里的this指针指向window
单击new element时,弹出对话框显示new element text!
  ——因为这时toString函数里的this指针指向div元素,而该元素已经定义了m_Text成员(this.newElement.m_Text = "new element text!")
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics