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

Javascript 这种创建对象的方法是否仅适用于单例对象?,javascript,javascript-objects,Javascript,Javascript Objects,我正在看道格拉斯·克罗克福德写的一些代码。他使用下面的结构来创建对象 var obj = (function(){ var x, y, z; // These are private fields // This is private method function func1() { } return { // This is public method init : function() { }

我正在看道格拉斯·克罗克福德写的一些代码。他使用下面的结构来创建对象

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();
我不喜欢构造函数方法,因为您需要使用_uuu来表示私有字段或方法(这并没有真正使字段私有),并且您需要使用这个关键字来访问任何字段或方法。我喜欢第一种方法,但我不知道如何使用它定义多个对象


我们可以在第一个方法中定义多个对象,还是只能用于创建单例对象?

要实例化新对象,您需要使用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 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=newObj()。不确定两者之间的含义是什么,但我通常只使用一个函数。

请注意:

this.__x
不将x私有化(除非按照惯例可能,即人们学会不使用x)

而是:

function Obj() {
    //  private
    var x = 0;
    var __y = 0;

    // public
    this.z = 0;

    // Private method
    function func1() {
    };

    // Public method
    this.init = function() {
    }
}

我发现这个链接很有帮助:

你是说在很多obj实例中有多个对象吗?@adriaanp是的,我是说有多个实例