Skip to content

Instantly share code, notes, and snippets.

@sebabelmar
Last active April 19, 2016 16:37
Show Gist options
  • Save sebabelmar/e24d1a3787c5015a9d79c32a59cbe38d to your computer and use it in GitHub Desktop.
Save sebabelmar/e24d1a3787c5015a9d79c32a59cbe38d to your computer and use it in GitHub Desktop.

The jQuery identifier (or $) is just a constructor function, and all instances created with it, inherit from the constructor's prototype.

###A simple constructor function:

function Test() {
  this.a = 'a';
}
Test.prototype.b = 'b';

var test = new Test(); 
test.a; // "a", own property
test.b; // "b", inherited property

A simple structure that resembles the architecture of jQuery:

(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"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment