1. 程式人生 > >牛客網_返回物件

牛客網_返回物件

這裡寫圖片描述
我的答案:

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(); }