js基礎練習題 模塊


題目描述

完成函數 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;
}

要點

聲明對象有兩種常見的方式:var obj = {};和var obj = new Object();。前面一種可以直接在括號中以key:value的方式定義屬性,后一種采用點運算符給對象添加屬性。
1
2
3
4
5
6
7
8
9
10
11
function createModule(str1, str2) {
      var obj = {
          greeting : str1,
          name     : str2,
          sayIt    : function(){
              //兩個屬性前面都需要加上this
              return this .greeting+ ", " + this .name;
          }
      };
      return obj;
  }

 

原型模式:
1
2
3
4
5
6
7
8
9
function createModule(str1, str2) {
     function Obj()
     {
         this .greeting = str1;
         this .name = str2;
     }
     Obj.prototype.sayIt =  function (){ return this .greeting +  ", " this .name;}
     return new Obj(); 
}
構造函數模式:
1
2
3
4
5
6
7
8
9
function createModule(str1, str2) {
     function Obj()
     {
         this .greeting = str1;
         this .name = str2;
         this .sayIt =  function (){ return this .greeting +  ", " this .name;}
     }
     return new Obj();   
}
創建對象模式:
1
2
3
4
5
6
7
8
9
10
11
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();   
}
字面量模式:
1
2
3
4
5
6
7
8
9
function createModule(str1, str2) {
     var obj =
             {
                 greeting : str1,
                 name : str2,
                 sayIt :  function (){ return this .greeting +  ", " this .name;}
             };
     return obj;   
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM