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.