|
<HTML>
<HEAD>
<TITLE> Class (Object-Oriented) </TITLE>
<script src="prototype.js" type="text/javascript"></script>
</HEAD>
<BODY>
<script>
//Person类
var Person = Class.create(
{
initialize : function(name)
{
//属性在这初始化
this.name = name;
},
//方法初始化
getName : function()
{
return this.name;
}
});
//User类继承自Person
var User = Class.create(Person,
{
initialize : function($super,name,age)
{
//相当于this.name = name;
$super(name);
this.age = age;
},
//在创建时添加访求
getAge : function()
{
return this.age;
}
});
//也可以通过addMethods方法来添加方法
User.addMethods({
show : function()
{
alert("username:" + this.name + ",age:" + this.age);
}
});
var me = new User("zdw",99);
alert(me.getName() + "," + me.getAge());
me.show();
//动物类
var Animal = Class.create(
{
initialize : function(name,sound)
{
this.name = name;
this.sound = sound;
},
speak : function()
{
alert(this.name + " says: " + this.sound + "!");
}
}
);
//蛇继承自动物
var Snake = Class.create(Animal,
{
initialize : function($super,name)
{
$super(name,"hissssssssssss");
}
});
//眼镜蛇
var ringneck = new Snake("Ringneck");
ringneck.speak();
//响尾蛇
var rattlesnake = new Snake("Rattler");
rattlesnake.speak();
//重写自己的迭代
var AnimalPen = Class.create(Enumerable,
{
initialize : function()
{
//将实参转换为数组
var args = $A(arguments);
//查看传入参数是否都是动物类的实例
if(!args.all(function(arg){return arg instanceof Animal}))
throw "Only animals in here!";
this.animals = args;
},
_each : function(iterator)
{
return this.animals._each(iterator);
}
});
var snakePen = new AnimalPen(ringneck,rattlesnake);
snakePen.invoke('speak');
</script>
</BODY>
</HTML>
|