单个对象
- 创建自定义对象
var person = new object();
person.name = 'Lily';
person.age = 28;
person.job = 'softwork';
person.sayName = function(){
alert(this.name)
}
- 创建对象字面量
var person = {
name : 'Lily',
age : 28,
job : 'softwork',
sayName:function(){
alert(this.name);
}
}
变体
- 工厂模式
function plant(name,age,school){
var o = new object();
o.name = name;
o.age = age;
o.school = school;
o.getinfo = function(){
console.log(this.name + '的年龄是:'+this.age+',学校是:'+this.school);
};
return o;
}
var myinfo = plant('tom','20','qinghua');
myinfo.getinfo();
- 构造函数模式
function consutrction(name,age,school){
this.name = name;
this.age = age;
this.school = school;
this.getinfo = function(){
console.log(this.name + '的年龄是:'+this.age+',学校是:'+this.school);
};
}
var myinfo = new consutrction('lisa','22','beida');
//var myinfo2 = new consutrction('lisa','22','beida');
myinfo.getinfo();
- 原型模式
function proto(){}
proto.prototype = {
name:'json',
age:'23',
school:'ligong',
getinfo:function(){
console.log(this.name + '的年龄是:'+this.age+',学校是:'+this.school);
}
}
var myinfo = new proto();
myinfo.getinfo();
- 构造函数模式+原型模式
function person(name,age,school){//属性
this.name = name;
this.age = age;
this.school = school;
}
person.prototype = {//方法
getinfo:function(){
console.log(this.name + '的年龄是:'+this.age+',学校是:'+this.school);
},
getjob:function(){
//content
}
}
var myinfo = new person('jim',35,'beida');
myinfo.getinfo();
- 寄生构造模式
function object(){
var arr = new Array();
arr.push.apply(arr,arguments);
arr.getTostring = function(){
return this.join(",");
}
return arr;
}
var o = new object('name','age','school');
console.log(o.getTostring());