Javascript 使用 Apply 和 Return This 的模块

Javascript Module Using Apply and Returning This

我一直在不断寻找最简单的 Javascript 模块模式。我已经阅读了几乎所有我能找到的文章。大多数模块模式喜欢创建一个对象,向其添加函数,然后 return 该对象并公开 public 方法,如下所示:

var Module = (function() {
    var exports = {}, x = 1;

    function private() {
        return x;
    }

    exports.public = function() {
        return x;
    };

    return exports;
}());

从长远来看,这似乎是一种痛苦,所以我一直在寻找一种更简单的方法。我已经看到我可以调用 apply 函数,并传入一个对象,然后使用 "this" 来引用它,并使用 return "this" 来获得相同的效果,如下所示:

var Module = (function() {
    var x = 1;

    function private() {
        return x;
    }

    this.public = function() {
        return x;
    };

    return this;
}).apply({});

使用apply并传入一个空对象有什么问题吗?这似乎是最好的方法,因为 "this" 关键字与 JS Intellisense 着色相得益彰,而且似乎更容易理解。有人看到这有什么问题或有更简单的方法吗?

This seems like the best way as the "this" keyword goes nicely with JS Intellisense coloring

这真的不应该成为任何理由:-)

seems to be easier to understand.

实际上对我来说不是。 this 通常只用在构造函数和对象方法中,而不用在 IEFE 中(除非它在 ​​IEFE 之外与 this 相同,即全局对象)。因此,要了解您在这里做什么,我必须向下滚动到文件末尾以了解该函数的调用方式。

Anybody see any problems with this

是的。除了不寻常之外,它还剥夺了您对模块对象的静态本地引用。如果您想从模块中的某处调用您的 public 方法之一,您可以使用 this(在其他 public 方法中)或 Module,但 neither of them works the same 作为 exports.

or have a simpler way?

您也可以混合使用这两种模式:

var Module = (function(exports) {
    var x = 1;

    function private() {
        return x;
    }

    exports.public = function() {
        return x;
    };

    return exports;
}({}));