创建 JavaScript 对象
通过 JavaScript,您能够定义并创建自己的对象。
创建新对象有两种不同的方法:
定义并创建对象的实例
使用函数来定义对象,然后创建新的对象实例
创建直接的实例
这个例子创建了对象的一个新实例,并向其添加了四个属性:
方式一:
window.=function () {
var person = new Object();
person.firstname="Bill";
person.lastname="Gates";
person.age=56;person.eyecolor="blue";// document.write()想页面中输出信息
document.write(person.firstname + " is " + person.age + " years old.");
}方式二:
var person={
firstname:"John",
lastname:"Doe",
age:50,
eyecolor:"blue"
};使用对象构造器
本例使用函数来构造对象:
function person(firstname,lastname,age,eyecolor){
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
}
var myFather=new person("Bill","Gates",56,"blue");
document.write(myFather.firstname + " is " + myFather.age + " years old.");如有不足请多多指教!希望给您带来帮助!