Thursday, October 17, 2013

JQuery Architecture

I found the following code example on JQuery's architecture and found it very helpful. One thing to note is the great use of ensuring JQuery is always called with a new instance. Relevant snippet is the following:
if (!(this instanceof foo))
      return new foo(arg);

(function() {
  var foo = function(arg) { // core constructor
    // ensure to use the `new` operator
    if (!(this instanceof foo))
      return new foo(arg);
    // store an argument for this example
    this.myArg = arg;
    //..
  };

  // create `fn` alias to `prototype` property
  foo.fn = foo.prototype = {
    init: function () {/*...*/}
    //...
  };

  // expose the library
  window.foo = foo;
})();

// Extension:

foo.fn.myPlugin = function () {
  alert(this.myArg);
  return this; // return `this` for chainability
};

foo("bar").myPlugin(); // alerts "bar"
http://stackoverflow.com/questions/4083351/what-does-jquery-fn-mean

No comments:

Post a Comment