2

I have a prototyped function that i would like to use it in a limited scope in order to provide it with a jquery plugin.

//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);

Is that possible?

Thanks

4

1 回答 1

1

是的,只需将您的代码包装在 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?
}());
于 2015-03-27T15:21:12.430 回答