我的答案:
function createModule(str1, str2) {
/*var obj={
greeting:str1,
name:str2,
sayIt :function(){
return this.greeting+", "+this.name;
}
};
return obj;*/
//工厂模式
/* var obj=new Object();
obj={
greeting:str1,
name:str2,
sayIt :function(){
return this.greeting+", "+this.name;
}
}
return obj;*/
//构造函数模式
/*function CreateObj(){
this.greeting=str1;
this.name=str2;
this.sayIt=function(){
return this.greeting+', '+this.name;
}
}
return new CreateObj();*/
//原型模式
/*function CreateObj(){
}
CreateObj.prototype.greeting=str1;
CreateObjt.prototype.name=str2;
CreateObj.prototype.sayIt=function(){
return this.greeting+', '+this.name;
}
return new CreateObj();*/
//更简单的原型方法,字面量创建原型对象
/*function CreateObj(){
}
CreateObj.prototype={
greeting:str1,
name:str2,
sayIt:function(){
return this.greeting+', '+this.name;
}
}
Object.defineProperty(CreateObj.prototype,"constructor",{
enumerable:false,
value:CreateObj
})
return new CreateObj();*/
//组合使用构造函数模式和原型模式
/*function CreateObj(){
this.greeting=str1;
this.name=str2;
}
CreateObj.prototype.sayIt=function(){
return this.greeting+', '+this.name;
}
return new CreateObj();*/
//动态原型模式,,对上述方法进行封装
/*function CreateObj(){
this.greeting=str1;
this.name=str2;
if(typeof this.sayIt !=="function"){
CreateObj.prototype.sayIt=function(){
return this.greeting+', '+this.name;
}
}
}
return new CreateObj();*/
//寄生构造函数模式
/*function CreateObj(){
var o=new Object();
o.greeting=str1;
o.name=str2;
o.sayIt=function(){
return this.greeting+', '+this.name;
}
return o;
}
return new CreateObj();*/
//稳妥构造函数模式
function CreateObj(){
var o=new Object();
o.greeting=str1;
o.name=str2;
o.sayIt=function(){
return o.greeting+', '+o.name;
}
return o;
}
return CreateObj();
}
更多讨论:
https://www.nowcoder.com/questionTerminal/48e53feaabe94506a61300edadb5496d