2006-11-29

js中的原型

前几天发现js中的原型功能实在是太强大了

一。创建自己的原型

function Root(){

this.id="1001";//为Root类定义属性,并初始化

this.name="this is name";//为Root类定义属性,并初始化

this.add=function (name2){

this.name=this.name+name2;//为Root类添加方法

}

}

下面来看看如何使用原型:

function test(){

var root=new Root();//可以知道function Root()相当于java中的构造函数,也相当于java中的一个类

alert(root.id);//得到js对象的属性

alert(root.name);//得到js对象的属性

}

还有别的方式:

Robot.prototype.hasJetpack = false;Robot.prototype.actionValue = "Intruders beware!";Robot.prototype.doAction = function() { alert(this.actionValue); };function Robot(flying, action) {   if (flying == true)      this.hasJetpack = true;   if (action)      this.actionValue = action;}

二。为已有的js数据类型加上函数

这是原型的另一个使用

String.prototype.getThirdChar = function()
{
?? return this.charAt(2);
}

评论
发表评论

您还没有登录,请登录后发表评论

letle
搜索本博客
存档
最新评论