nikk wong
nikk wong

Reputation: 8670

jQuery structure and understanding this

I'm going through some pseudo-jquery code—and though I understand this for the most part, some of the implementations are confusing. I ran into this pseudocode, which is meant to explain how jQuery works:

(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"

It isn't instantly obvious to me what this in (!(this instance of foo)) or this.myArg = arg; is.

My initial impression is that this code is referenced every time an instance of foo is ran, i.e. foo("bar").myPlugin();.

Going off that assumption, this commonly refers to the object that owns the method, but in this case, if foo owns this (understanding that foo is pseudo for jQuery), jQuery.myArg = arg doesn't really make much sense. That would mean every time you invoke foo i.e. foo("bar").myPlugin(); it instantiates foo.bar and to further the example at the bottom, foo.bar.myPlugin is an actual property instantiated from foo?

Simultaneously, this instanceof foo, ie. jQuery instanceof jQuery seems redundant.

What am I missing here? Appreciate any help/direction.

Upvotes: 0

Views: 63

Answers (1)

Bartosz Gościński
Bartosz Gościński

Reputation: 1580

tl;dr

foo is an constructor function and we ensure it's always invoked like so.

explanation

foo is an constructor function. When called with new keyword the body of foo function will be executed in context of new instance of foo class (this will be pointing to this new instance). So:

this instanceof foo === true

When called without the new keyword the context will be windowand normally no new object would be created.

Via

if (!(this instanceof foo))
  return new foo(arg);

we ensure that even if one omits new keyword we return new instance of foo.

Upvotes: 2

Related Questions