pjs
pjs copied to clipboard
#20 breaks subclassing jQuery
Unclear whether this is worth "fixing" (whatever that means), but I think it's worth at least discussing even if we decide just to document a workaround.
If you subclass jQuery with Pjs, many methods that aren't supposed to mutate this
, like .appendTo()
, will add elements to this
: http://jsbin.com/faxifed/edit?html,console,output
This was causing exponentially growing jQuery sets in MathQuill (https://github.com/mathquill/mathquill/pull/629).
This is because jQuery internally calls this.constructor()
which normally creates a whole new jQuery object, but for Pjs subclasses starting with #20 on v5.0.0 just returns this
: https://github.com/jquery/jquery/blob/305f193aa57014dc7d8fa0739a3fefd47166cd44/src/core.js#L72-L84
Thanks @jwmerrill!
Seems like the main reason jQuery can be subclassed "idiomatically" (i.e. the reason Coffeescript and ES6 classes don't break here) is because they allow constructors to return objects: http://jsbin.com/qinare/edit?html,console,output
However, they're not "well-behaved" subclasses, since if you try to instantiate them you get a jQuery object that isn't an instance of the subclass.