1

I'm working on building a collection of prototype helper methods inside a wrapper. However for ease of use, I'd like to be able to call the object as both a new instance and single global instance under the same call.

For example, with jQuery, you can call both "$" and "$()" which can be used differently http://learn.jquery.com/using-jquery-core/dollar-object-vs-function/:

So given the bellow as simple example, how could I do something similar?

(function () {

        var myWrapper = function (foo) {
            return new helper(foo);
        };

        var helper = function (foo) {
           this[0] = foo;
           return this;
        }

        helper.prototype = {
            putVar: function(foo) {
               this[0] = foo;
            }
        }

        if(!window.$) {
            window.$ = myWrapper;
        }

})();

// create an new instace;
var instance = $("bar");
console.log(instance);

// call a prototype method
instance.putVar("foo");
console.log(instance);

// call a prototype method using the same call without new instance 
// this doesnt work :(
$.putVar("foo");

// however this will work
window.myLib = $("foo");
myLib.putVar("bar");

http://jsfiddle.net/2ywsunb4/

user3143218
  • 1,738
  • 5
  • 32
  • 48

1 Answers1

0

If you want to call $.putVar, you should define putVar like this:

myWrapper.putVar = function (foo) {
    console.log('Work');
}

In your code, the instance and myLib are the same thing, they are both instances created by you.

If you want to call both $.putVar and $(...).putVar, you should add the code I show you above. That means you have to define two putVar functions, one is used like a 'instance' method, while the other one is used like a 'static' method.

If you search through jQuery source code, you will see two each functions defined. That's why you can all both $.each(...) and $(...).each for different usages.

Mouhong Lin
  • 4,402
  • 4
  • 33
  • 48
  • that adds the function directly into instance, i want to keep it in the prototype – user3143218 Feb 14 '15 at 09:17
  • I think this is the only way in which you can call both `$(...).putVar` and `$.putVar`. You define `putVar` in the prototype, how can you expect it to work by directly calling `$.putVar`? `$` is just an alias of `myWrapper` in your code, it's a function. – Mouhong Lin Feb 14 '15 at 13:45