练习牛客网笔试题--前端js--42-模块
// 题目描述
// 完成函数 createModule,调用之后满足如下要求:
// 1、返回一个对象
// 2、对象的 greeting 属性值等于 str1, name 属性值等于 str2
// 3、对象存在一个 sayIt 方法,该方法返回的字符串为 greeting属性值 + ', ' + name属性值
1.自己的练习
function createModule(str1, str2) {
return {
greeting: str1,
name: str2,
sayIt: function() {
return this.greeting + ', ' + this.name;
}
}
}
2.题解
// 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;
}