题目描述
完成函数 createModule,调用之后满足如下要求:
1、返回一个对象
2、对象的 greeting 属性值等于 str1, name 属性值等于 str2
3、对象存在一个 sayIt 方法,该方法返回的字符串为 greeting属性值 + ', ' + name属性值
声明对象有两种常见的方式:var obj = {};和var obj = new Object();。
前面一种可以直接在括号中以key:value的方式定义属性,后一种采用点运算符给对象添加属性。
1.原型模式:
function createModule(str1, str2) {
function Obj()
{
this.greeting = str1;
this.name = str2;
}
Obj.prototype.sayIt = function(){return this.greeting + ", " + this.name;}
return new Obj();
}
2.构造函数模式:
function createModule(str1, str2) {
function Obj()
{
this.greeting = str1;
this.name = str2;
this.sayIt = function(){return this.greeting + ", " + this.name;}
}
return new Obj();
}
3.创建对象模式:
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();
}
4.字面量模式:
function createModule(str1, str2) {
var obj =
{
greeting : str1,
name : str2,
sayIt : function(){return this.greeting + ", " + this.name;}
};
return obj;
}
本文介绍四种常见的JavaScript模块创建方法:原型模式、构造函数模式、创建对象模式和字面量模式,详细解析每种模式的实现方式及特点。

被折叠的 条评论
为什么被折叠?



