function Foo(){
this.x=1;
}
这既是一个函数,也是一个对象;
可以使用obj = new Foo;实例化这个对象
function Foo(){
this.x=1;
this.getx = function(){
return this.x;
}
}
给对象Foo添加了一个方法getx;模仿前面的例子,可以用obj.getx()来调用
Foo.prototype.x=2;
Foo.prototype.y=3;
Foo.prototype.gety = function(){return this.y;}
对一个对象来说如果,如果在prototype后面跟着属性,表示给对象内的属性x重新赋值,或者新建一个属性y,或者添加一个方法gety。
Foo.prototype = new MainFoo;
这种情况,表示让Foo继承父类MainFoo。
下面是一个对象继承例子(http://www.matrix.org.cn/resource/article/1500.html)
<script language="javascript">
//*********************************************
// 定义Pet(宠物)对象
//*********************************************
function Pet() {
//名称
this.name = null;
//颜色
this.color = null;
//获取名称
this.getName = function() {
return this.name;
};
//设置名称
this.setName = function(newName) {
this.name = newName;
};
//获取颜色
this.getColor = function() {
return this.color;
};
//设置颜色
this.setColor = function(newColor) {
this.color = newColor;
};
//定义一个需要实现的方法
this.getFood = null;
//获取宠物的描述信息
this.toString = function() {
return "The pet is " + this.name +",it's "+this.color+",and it likes "+this.getFood()+".";
};
}
//*********************************************
// 定义Cat(猫)对象
//*********************************************
function Cat() {
//实现Pet中定义的getFood方法
this.getFood = function() {
return "fish";
};
}
//声明Cat的原型,即Cat的父类
Cat.prototype = new Pet;
//*********************************************
// 定义PersianCat(波斯猫)对象
//*********************************************
function PersianCat() {
}
//声明PersianCat的原型,即PersianCat的父类
PersianCat.prototype = new Cat;
//重载Pet的toString方法
PersianCat.prototype.toString = function() {
return "It's just a persian cat.";
};
//*********************************************
// 定义Dog(狗)对象
//*********************************************
function Dog() {
//实现Pet中定义的getFood方法
this.getFood = function() {
return "bone";
};
}
//声明Dog的原型,即Dog的父类
Dog.prototype = new Pet;
</script >
<script language="javascript">
//定义一个Cat对象
var cat = new Cat();
cat.setName("MiMi");
cat.setColor("white");
//定义一个Dog对象
var dog = new Dog();
dog.setName("WangWang");
dog.setColor("yellow");
//定义一个PersianCat对象
var persianCat = new PersianCat();
//定义数组,保存上面的三个对象
var pets = new Array(3);
pets[0] = cat;
pets[1] = dog;
pets[2] = persianCat;
//测试程序
for(var i=0,size=pets.length;i<size;i++) {
alert(pets[i].toString());
}
</script>
还可以看看http://www.daima.com.cn/Info/55/Info14537/ ,
http://coolcat.cnblogs.com/archive/2005/12/20/301062.html (更详细讲解prototype原理)