closures - Javascript 模块使用 Apply 并返回 this

标签 closures module-pattern javascript

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

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

    function private() {
        return x;
    }

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

    return exports;
}());

从长远来看,这似乎会很痛苦,所以我一直在寻找一种更简单的方法。我已经看到我可以调用 apply 到该函数,并传入一个对象,然后使用“this”来引用它并返回“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作为导出

or have a simpler way?

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

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

    function private() {
        return x;
    }

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

    return exports;
}({}));

关于closures - Javascript 模块使用 Apply 并返回 this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30180179/

相关文章:

javascript - 根据输入参数调用嵌套函数

Groovy .each 闭包将元素包装在不需要的 Object[] 中

javascript - 在模块中重新声明变量还是引用单独的模块更好?

javascript - 公众投票和避免多次投票 : using cookies or IP?

java - 闭包参数 : how to specify generic types for closure parameter in groovy

clojure - 什么时候使用 Clojure 的闭包?

javascript 模块模式适用于 jsbin,但不适用于我的服务器/浏览器

需要 JavaScript 设计模式帮助 : Loose Augmentation of Modules

javascript - 在渲染函数中调用返回 JSX 元素的函数

php - Tinymce Enter 键