JavaScript 创建和使用自定义对象 - 通过定义对象的构造函数

下面的实例是通过定义对象的构造函数的方法和使用new 操作符所生成的对象实例,先考察其代码:[code]<! DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.0//EN”
http://www.w3.org/TR/REC-html140/strict.dtd”>

Sample Page!
[/code]程序运行结果如图所示。

在该方法中,用户必须先定义一个对象的构造函数,然后再通过new 关键字来创建该对象的实例。

定义对象的构造函数如下:function School(iName,iAddress,iGrade,iNumber) { this.name=iName; this.address=iAddress; this.grade=iGrade; this.number=iNumber; this.information=showInformation; }当调用该构造函数时,浏览器给新的对象分配内存,并隐性地将对象传递给函数。

this 操作符是指向新对象引用的关键词,用于操作这个新对象。

下面的句子:this.name=iName;该句使用作为函数参数传递过来的iName 值在构造函数中给该对象的name 属性赋值,该属性属于所有School 对象,而不仅仅属于School 对象的某个实例如上面中的GKJDX。

对象实例的name 属性被定义和赋值后,可以通过如下方法访问该实例的该属性:var str=ZGKJDX.name;使用同样的方法继续添加其他属性address、grade、number 等,但information 不是对象的属性,而是对象的方法:this.information=showInformation;方法information 指向的外部函数showInformation 结构如下:function showInformation() { var msg=""; msg="自定义对象实例:\n" msg+="\n 机构名称 : "+this.name+" \n"; msg+="所在地址 : "+this.address +"\n"; msg+="教育层次 : "+this.grade +" \n"; msg+="在校人数 : "+this.number window.alert(msg); }同样,由于被定义为对象的方法,在外部函数中也可使用this 操作符指向当前的对象,并通过this.name 等访问它的某个属性。

在构建对象的某个方法时,如果代码比较简单,也可以使用非外部函数的做法,改写School 对象的构造函数:function School(iName,iAddress,iGrade,iNumber) { this.name=iName; this.address=iAddress; this.grade=iGrade; this.number=iNumber; this.information=function() { var msg=""; msg="自定义对象实例:\n" msg+="\n 机构名称 : "+this.name+" \n"; msg+="所在地址 : "+this.address +"\n"; msg+="教育层次 : "+this.grade +" \n"; msg+="在校人数 : "+this.number; window.alert(msg); }; }