自定义JavaScript类

本文介绍了JavaScript中三种创建对象的方法:工厂方式、构造函数方式及原型方式,并对比了它们的特点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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();//使用原型方式的另一个好处是可以为已经存在的类添加新的成员

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值