3

When I first started writing my own code I never understand jQuery's 'enhanced' init constructor until later on so I stuck to a different way of constructing my objects. I was wondering if I should keep my old ways or start using my own 'enhanced' init constructor.


My Constructor:

var $ = function(selector,context,createObj) {
        if(createObj) {
           // actually initiating object
        } else {
           return new $(selector,context,true);
        }
};

jQuery:

jQuery = function( selector, context ) {
    // The jQuery object is actually just the init constructor 'enhanced'
    return new jQuery.fn.init( selector, context, rootjQuery );
};

Actual Init:

init: function( selector, context, rootjQuery ) {
    // some code
}

Changing prototype (jQuery.prototype.init.prototype=jQuery.prototype):

jQuery.fn.init.prototype = jQuery.fn;
Matt Coughlin
  • 18,666
  • 3
  • 46
  • 59
FrameDev
  • 61
  • 1
  • 8

1 Answers1

2

jQuery's constructor pattern is historically grown and bad practise - or at least unnecessarily complicated. If you want a constructor that works well without new (if applied wrong), use

function $(selector, context) {
    if (this instanceof $) {
        // actually initiating object
    } else {
        return new $(selector, context);
    }
}
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • So with analogy to **[my code]**(http://stackoverflow.com/questions/23184344/javascripts-super-constructor-clarification) - you will start add methods at line #3 in your code ? `if (this instanceof $) { this.foo=function (){...}...}` ? – Royi Namir Apr 22 '14 at 16:09
  • Yes, exactly. Or you do an early return and just prepend your usual constructor by `if (!(this instanceof $)) return new $(…);` – Bergi Apr 22 '14 at 17:14