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;   
}
posted @ 2017-12-28 16:09  是两页啊  阅读(1334)  评论(0编辑  收藏  举报