200814/07

Javascript的动态性 Published by bugx 22:04:04 七月 14th,2008 in web种种.

ruby是一种动态语言,众所周知。大家似乎忽略了javascript也是动态的哦,这就使得javascript变得非常的灵活和强大。动态语言的优点就是在在类外部对类进行扩展,甚至对对象动态的增加方法。据说net3加入了这种特性,我还未验证过。

动态的增加方法,要比继承更好用,但是又和类的封闭性似乎有所冲突。来看一下js的动态给类增加方法

class1 = function(){
 var m1="m1的值";
 var m2="m2的值";
 function method1 ()
 {
  alert(m1);
 }
 function method2()
 {
  alert(m2);
 }

 this.m3="m3";

 this.method3 = function()
 {
  alert(m2);
 }

//测试构造函数
 {
 method1();
 method2();
 }
 
}

//类外部给类增加方法,

class1.prototype.method4=function()
{
 alert(this.m3);
}
 var o = new class1();
 alert (o.m3);
 o.method3();
  o.method4(); 

但是这种方法是不能访问类的私有变量的。这又是符合类的封闭性的原则的。

js  动态语言  

此文发于 2008-7-14 22:04:04,归类于 web种种,已阅读
Trackback引用地址:http://blog.nowans.com/trackback.asp?id=220
日志评论Feed地址:http://blog.nowans.com/feed.asp?o=comment&id=220

1条留言针对“Javascript的动态性” 订阅评论 发表评论

假使你有话要讲,我想我还不至于拦着你罢: