引題:
完成函數 createModule,調用之後滿足如下要求:
1、返回一個對象
2、對象的 greeting 屬性值等於 str1, name 屬性值等於 str2
3、對象存在一個 sayIt 方法,該方法返回的字符串爲 greeting屬性值 + ‘, ’ + name屬性值
解決方案:
- 法一:字面量形式
function createModule(str1, str2) {
var obj =
{
greeting : str1,
name : str2,
sayIt : function(){return this.greeting + ", " + this.name;}
};
return obj;
}
- 法二:創建對象模式
function createModule(str1, str2) {
function CreateObj()
{
obj = new Object;
obj.greeting = str1;
obj.name = str2;
obj.sayIt = function(){return this.greeting + ", " + this.name;}
return obj;
}
return CreateObj();
}
- 法三:原型模式
function createModule(str1, str2) {
function Obj()
{
this.greeting = str1;
this.name = str2;
}
Obj.prototype.sayIt = function(){return this.greeting + ", " + this.name;}
return new Obj();
}
- 法四:構造函數模式
function createModule(str1, str2) {
function Obj()
{
this.greeting = str1;
this.name = str2;
this.sayIt = function(){return this.greeting + ", " + this.name;}
}
return new Obj();
}