I'm writing a jQuery plugin, and I was wondering how to make sure that I don't ever overwrite a future jQuery native method.
For example, my plugin is called Foo and usage is $('selector').foo()
.
jQuery 2.6 has noticed the popularity of Foo and decided that it will include it in the core package. It too is used via $('selector').foo()
.
I don't want my Foo to overwrite jQuery's native Foo (or else clash).
This is what I came up with...
(function($) {
// If jQuery adds this method, we don't want to overwrite it
if (typeof $.foo === 'function') {
return;
};
$.fn.foo = function() {
// Foo
};
})(jQuery);
Would this be the best way to do it?
A jQuery plugin is simply a new method that we use to extend jQuery's prototype object. By extending the prototype object you enable all jQuery objects to inherit any methods that you add. As established, whenever you call jQuery() you're creating a new jQuery object, with all of jQuery's methods inherited.
The $ represents the jQuery Function, and is actually a shorthand alias for jQuery .
How to use Plugins. To make a plug-in's methods available to us, we include plug-in file very similar to jQuery library file in the <head> of the document. We must ensure that it appears after the main jQuery source file, and before our custom JavaScript code.
You can skip the if
statements and build definition-checking into your function declaration.
(function($){
$.fn.foo = $.fn.foo || function () {
// only used if $.fn.foo is undefined
}
})(jQuery)
I think you would be better off with:
if ($.foo !== undefined) {
alert('there is something at foo');
return;
};
The reason being, your plugin could look like this:
$.foo = {
doSomething: function() { /* do something*/ },
doSomethingElse: function() { /* do something else*/ }
};
The typeof
the above is not function, but object, so the condition in your example will not behave as you expect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With