完成函数 createModule,调用之后满足如下要求:
1、返回一个对象
2、对象的 greeting 属性值等于 str1, name 属性值等于 str2
3、对象存在一个 sayIt 方法,该方法返回的字符串为 greeting属性值 + ', ' + name属性值
function createModule(str1, str2) { var res = { greeting: str1, name: str2, sayIt: function(){ return this.greeting + ", " + this.name; } } return res; }
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(); }创建对象模式:
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) { var obj = { greeting : str1, name : str2, sayIt : function(){return this.greeting + ", " + this.name;} }; return obj; }
//使用构造函数法 function createModule(str1, str2) { function Obj(){ this.greeting = str1; this.name = str2; this.sayIt = function(){ return this.greeting + ', ' + this.name; }; } return new Obj(); } //构造函数与原型组合 function createModule(str1, str2) { function CreateMod(){ this.greeting = str1; this.name = str2; } CreateMod.prototype.sayIt = function(){ return this.greeting + ', ' + this.name; } return new CreateMod(); }
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 CreateObj() { obj = new Object; obj.greeting = str1; obj.name = str2; obj.sayIt = function(){return this.greeting + ", " + this.name;} return obj; } return CreateObj(); }还非得自己又整个函数,请问这个函数有可复用的机会吗,new Object干啥呢,非得一个个添加属性。另外变量还用隐式全局声明,真的是把es5及其之前的糟粕学得透透的。最可笑还有这个
function createModule(str1, str2) { var P = { greeting : str1, name : str2, sayIt : function(){return this.greeting + ", " + this.name;} }; var p = Object.create(P); return p; }如果说new object和字面量只是习惯问题的话,那这哥们的做法我真是看不懂。新建了个对象p,原型指向了P,真的是笑死我了,p对象本身啥属性也没有,访问还得靠原型链查找P,你要上天啊,关键这哥们还信誓旦旦说创建对象只有两种方式,构造函数和这个。。。你学岔劈了吧,你要说用这两方式来模拟实现类还靠点谱
function createModule(str1, str2) { var greeting = str1; var name = str2; function sayIt(){ return this.greeting +", "+ this.name; } return { greeting: greeting, name: name, sayIt: sayIt } }
var foo = coolModule('Hello', 'World!');
foo.sayIt() // Hello, World!