这种创建对象的方法是否只适用于单例对象?

Is this method of creating objects only applicable for singleton objects?

本文关键字:适用于 单例 对象 是否 创建对象 方法      更新时间:2023-09-26

我正在浏览Douglas Crockford编写的一些代码。他使用下面的结构创建对象。

var obj = (function(){
    var x, y, z;   // These are private fields
    // This is private method
    function func1() {
    }
    return {
        // This is public method
        init : function() {
        }
    };
}());

相对于下面的构造函数,我更喜欢这种方式。

function Obj() {
    // Uses __ to denote private
    this.__x = 0;
    this.__y = 0;
    this.__z = 0;
    // Private method
    this.__func1 = function() {
    };
    // Public method
    this.init = function() {
    }
}
var obj = new Obj();

我不喜欢构造函数方法,因为你需要使用__来表示私有字段或方法(这并没有真正使字段私有),你需要使用这个关键字来访问任何字段或方法。我喜欢第一个方法,但我不知道如何使用它定义多个对象。

我们可以在第一个方法中定义多个对象吗?或者它只能用于创建单例对象?

要实例化新对象,需要使用new关键字,该关键字需要使用函数作为构造函数。我看到两个选项:

在函数中返回一个函数而不是对象字面值:

var obj = (function(){
    var x, y, z;   // These are private fields
    // This is private method
    function func1() {
        console.log("func1");
    }
    return function() {
        // This is public method
        this.init = function() {
            func1();
        }
    };
})(); 

或者不要使用自执行函数:

var obj = function(){
    var x, y, z;   // These are private fields
    // This is private method
    function func1() {
        console.log("func1");
    }
    return {
        // This is public method
        this.init = function() {
            func1();
        }
    };
};

都让我们执行var newObj = new obj()。不确定两者之间的含义,但我通常只是使用一个函数。

请注意:

this.__x

没有将x设为私有的(除非有可能按照约定,即人们学会不使用它)

:

function Obj() {
    //  private
    var x = 0;
    var __y = 0;
    // public
    this.z = 0;
    // Private method
    function func1() {
    };
    // Public method
    this.init = function() {
    }
}

我发现这个链接很有用:http://www.phpied.com/3-ways-to-define-a-javascript-class/