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();
但是这种方法是不能访问类的私有变量的。这又是符合类的封闭性的原则的。
在 线 人