1.直接定义并创建对象
//定义并创建对象
var person = new Object();
//通过为对象赋值,向已有对象添加新属性
person.firstname = "Bill";
person.lastname = "skye";
person.age = 18;
//向已有对象添加方法
person.mothod = function(){
return person;
}
document.writeln(person.firstname + " is " + person.age + " years old.");
document.writeln(JSON.stringify(person.mothod()));
结果图:
或:
var student = {
"firstname":"Bill",
"lastname":"skye",
"age":"19",
"sex":"girl"
};
//或者
//var student = {
// firstname:"Bill",
// lastname:"skye",
// age:"19",
// sex:"girl"
// };
document.writeln(student.firstname + " is a " + student.sex);
结果图:
或定义一个构造函数,然后在构造函数的原型中添加属性和方法
var teacher = function(){};
teacher.prototype = {
//属性
name:"lin",
age:23,
//方法
getage:function(){
return "getage";
}
}
var oneteacher = new teacher();
document.writeln(oneteacher.name + " is " + oneteacher.age + " years old.");
document.writeln(oneteacher.getage());
2.使用对象构造器来构造对象
function person(firstname,lastname,age)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
//定义对象的方法
this.changeName=changeName;
function changeName(name)
{
this.lastname=name;
}
}
myFather=new person("Bill","Gates",56);
document.write(myFather.firstname + " is " + myFather.age + " years old.");
myFather.changeName("Ballmer");
结果图: