javascript - 有没有办法在有限范围内对命名空间进行原型(prototype)设计?

标签 javascript jquery design-patterns prototype revealing-module-pattern

我有一个原型(prototype)函数,我想在有限的范围内使用它,以便为它提供一个 jquery 插件。

//Prototype
function StringBuilder(str) {
    this.value = str;
}
StringBuilder.prototype.append = function (str) {
    this.value = this.value + str;
    return this;
};

//jQuery plugin with Revealing module pattern
jQuery.NameOfThePlugin = (function () {
    //i would like to be able to use StringBuilder only in this scope
    helloWorld = new StringBuilder('Hello');
    helloWorld.append(' World');
})(window);

这可能吗?

谢谢

最佳答案

是的,只需包装您的代码in an IIFE这样您的 StringBuilder 仅在其范围内可用,而不是全局可用。然后 jQuery 插件向它导出一个闭包。

(function() {
    function StringBuilder(str) {
        this.value = str;
    }
    StringBuilder.prototype.append = function (str) {
        this.value = this.value + str;
        return this;
    };

    jQuery.NameOfThePlugin = function () {
        var helloWorld = new StringBuilder('Hello');
        helloWorld.append(' World');
        …
     }; // im pretty sure that plugin is supposed to be a function?
}());

您还可以在返回导出模块的地方使用实际的显示模块模式,在本例中为插件函数:

jQuery.NameOfThePlugin = (function() {
    function StringBuilder(str) {
        this.value = str;
    }
    StringBuilder.prototype.append = function (str) {
        this.value = this.value + str;
        return this;
    };

    return function () {
        var helloWorld = new StringBuilder('Hello');
        helloWorld.append(' World');
        …
     }; // im pretty sure that plugin is supposed to be a function?
}());

关于javascript - 有没有办法在有限范围内对命名空间进行原型(prototype)设计?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29302817/

相关文章:

java - Guava 18 无法使用 GWT 2.8Snapshot 和 Java 8 进行编译

javascript - Google chrome onbeforeunload 使用 iframe 的错误行为

jQuery:如何仅选择可见且已选中的复选框?

jquery - Internet Explorer 9.0 中的背景动画不显示动画

c# - builder 之间的继承——如何处理类型?

c++ - 从状态图框架中删除依赖项

javascript - 避免滚动条的 jQuery 图像视口(viewport)计算算法

javascript - 如何使用 jQuery 从 JSON 对象列出数组?

ios - 如何检查单例是否已经初始化?

javascript - dropzone.js - acceptedMimeTypes