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

Is there a way to prototype a namespace in a limited scope?

我有一个原型函数,我想在有限的范围内使用它,以便为它提供一个 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?
}());

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

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?
}());