1、工厂方式(动态添加类成员)
//建立student对象的工厂函数
function createStudent(id,xm,age)
{
var oStudent=new Object;
oStudent.id=id;
oStudent.xm=xm;
oStudent.age=age;
//定义study方法
oStudent.study=function()
{
alert(this.xm+'开始学习');
};
return oStudent;
}
调用函数
var oStudent=createStudnet('02','小明',12);
oStudent.study();
2、构造函数方式
//多个对象共享的study方法
function study()
{
alert(this.xm+'开始学习');
}
//Student类的构造方法
function Student(id,xm,age)
{
this.id=id;
this.xm=xm;
this.age=age;
this.study=study;
}
var oStudent =new Student('10','Mike',22);
oStudent.study();
3、原型方式
//建立一个空的构造方法
function Student()
{
}
//使用prototype为Student类添加属性
Student.prototype.id='12';
Student.prototype.xm='bill';
Student.protype.age=20;
//使用prototype为Student类添加方法
Student.prototype.study=function()
{
alert(this.xm+'开始学习');
};
var oStudent=new Student();
oStudent.study();//使用原型方式的另一个好处是可以为已经存在的类添加新的成员