Search code examples
javascriptjquerydesign-patternsprototyperevealing-module-pattern

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


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


Solution

  • Yes, just wrap your code in an IIFE so that your StringBuilder is only available in its scope, not globally. The jQuery plugin is then exporting a closure to it.

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

    You can also use the actual revealing module pattern where you return the exported module, in this example the plugin 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?
    }());