JS 创建实例对象的四种模式

需求

完成满足如下要求的函数:

  1. 返回一个对象
  2. 对象的 greeting 属性值等于 str1, name 属性值等于 str2
  3. 对象存在一个 sayIt 方法,该方法返回的字符串为 greeting属性值 + ‘, ‘ + name属性值

分析

js的原型系统,主要包含以下三个基本元素

属性

  1. prototype
  2. __ proto __
  3. constructor

原则

  1. 只有函数对象有prototype属性
  2. 变量的__ proto __属性返回的是它的构造函数的原型对象
  3. 变量的constructor属性返回的是它的构造函数

原型模式

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) {
        obj = new Object;
        obj.greeting = str1;
        obj.name = str2;
        obj.sayIt = function(){return this.greeting + ", " + this.name;}
        return obj;  
}

字面量

function createModule(str1, str2) {
    var obj =
            {
                greeting : str1,
                name : str2,
                sayIt : function(){return this.greeting + ", " + this.name;}
            };
    return obj;   
}

小结

原型模式与构造函数方法区别在于,前者原型方法是共享的,后者构造函数内的方法则是拷贝。而Object类与字面量模式,后者只不过是简写,使用了默认包装器。

本作品采用《CC 协议》,转载必须注明作者和本文链接
pardon110
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
开发者 @ 社科大
文章
134
粉丝
24
喜欢
101
收藏
55
排名:106
访问:8.9 万
私信
所有博文
社区赞助商