1.工厂模式
function
createObject(name,age){
var
obj =
new
Object();
obj.name = name;
obj.age = age;
obj.getName =
function
(){
return
this
.name;
};
obj.getAge =
function
(){
return
this
.age;
}
return
obj;
}
var
obj2 = createObject(
"王五"
,19);
console.log(obj2.getName());
console.log(obj2.getAge());
console.log(obj2.constructor);
2.构造函数法
function
Person(name,age,job){
this
.name = name;
this
.age = age;
this
.job = job;
}
Person.prototype = {
constructor:Person,
getName:
function
(){
return
this
.name;
},
getAge:
function
(){
return
this
.age;
},
getJob:
function
(){
return
this
.job;
}
}
var
p =
new
Person(
"二麻子"
,18,
"worker"
);
console.log(p.constructor);
console.log(p.getName());
console.log(p.getAge());
console.log(p.getJob());
function
Person(){
}
Person.prototype = {
constructor:Person,
name:
"张三"
,
age:21,
job:
"teacher"
,
getName:
function
(){
return
this
.name;
},
getJob:
function
(){
return
this
.job;
}
}
var
p =
new
Person();
console.log(p.getName());
//张三
console.log(p.getJob());
//teacher
var
p2 =
new
Person();
p2.name =
"李四"
;
console.log(p2.getName());
//李四
var
Dog = {
createDog:
function
(){
var
dog = {};
dog.name =
"汪汪"
;
dog.sayHello =
function
(){
console.log(
"Hello World!"
);
};
return
dog;
}
};
var
dog = Dog.createDog();
dog.sayHello();