javascript中this和with的用法

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

posted @ 2013-03-31 13:19  希望花开  阅读(189)  评论(0)    收藏  举报