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

CodeArtist
  • 5,534
  • 8
  • 40
  • 65
  • 2
    Do you mean `StringBuilder` itself, or just `StringBuilder.prototype.append`? If you mean the constructor itself just move the declaration inside that scope. If you don't then no, you can't. You could use a normal function within that scope instead. – James Allardice Mar 27 '15 at 14:18
  • @JamesAllardice if is a question then yes. I don't know how to do it... – CodeArtist Mar 27 '15 at 14:19
  • Sorry, I've edited my comment to make more sense. – James Allardice Mar 27 '15 at 14:21

1 Answers1

1

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?
}());
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375