Archive for August 5th, 2008

jQuery encourages using namespaces for methods in the $ namespace, like $.foo.bar() rather than $.bar(). This works for $ because methods don't expect this to refer to anything specific, and the way javascript works is to assign this to the last-named object, so in $.foo.bar(), this refers to $.foo.

This idea fails for plugins, however, since plugins expect this to refer to the jQuery object that started the chain. If I define $.fn.bar = function(){}, then when $(...).bar() is called, this refers to $(...), just as we want. But if I define $.fn.foo.bar = function(){}, then when $(...).foo.bar() is called, this refers to $(...).foo, which is an object that knows nothing about jQuery. There's no way to make an object reference return something else.

But all is not lost. We can define a function that returns an object, and that function can use this to set the returned object to be just like a jQuery object, but with the desired namespaced methods in it. The inefficient way to do that is to copy the new methods into the jQuery object, but if we can manipulate the prototype chain directly (as we can in Firefox) we can add our new methods to the chain without copying.

Continue reading ‘Namespaces in jQuery’ »