js模块基础练习题

 1 题目描述
 2 完成函数 createModule,调用之后满足如下要求:
 3 1、返回一个对象
 4 2、对象的 greeting 属性值等于 str1, name 属性值等于 str2
 5 3、对象存在一个 sayIt 方法,该方法返回的字符串为 greeting属性值 + ', ' + name属性值
 6 
 7 // 字面量模式
 8 function createModule(str1, str2) {
 9     var obj =
10             {
11                 greeting : str1,
12                 name : str2,
13                 sayIt : function(){return this.greeting + ", " + this.name;}
14             };
15     return obj;   
16 }
17 
18 //创建对象模式
19 function createModule(str1, str2) {
20     function CreateObj()
21     {
22         obj = new Object;
23         obj.greeting = str1;
24         obj.name = str2;
25         obj.sayIt = function(){return this.greeting + ", " + this.name;}
26         return obj;
27     }
28     return CreateObj();   
29 }
30 
31 //构造函数模式
32 function createModule(str1, str2) {
33     function Obj()
34     {
35         this.greeting = str1;
36         this.name = str2;
37         this.sayIt = function(){return this.greeting + ", " + this.name;}
38     }
39     return new Obj();   
40 }
41 
42 //原型模式
43 function createModule(str1, str2) {
44     function Obj()
45     {
46         this.greeting = str1;
47         this.name = str2;
48     }
49     Obj.prototype.sayIt = function(){return this.greeting + ", " + this.name;}
50     return new Obj(); 
51 }

猜你喜欢

转载自www.cnblogs.com/xiaole9924/p/11818707.html