【问题标题】:Is there a way to prototype a namespace in a limited scope?有没有办法在有限范围内对命名空间进行原型设计?
【发布时间】:2015-03-27 14:16:29
【问题描述】:

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

这可能吗?

谢谢

【问题讨论】:

  • 您是指StringBuilder 本身,还是只是StringBuilder.prototype.append?如果您的意思是构造函数本身,只需将声明移动到该范围内。如果你不那么不,你不能。您可以在该范围内使用普通函数。
  • @JamesAllardice 如果是一个问题,那么是的。我不知道该怎么做...
  • 抱歉,我已经编辑了我的评论以使其更有意义。

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


【解决方案1】:

是的,只需包装您的代码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?
}());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多