开发者

What is the best way to make sure a jQuery plugin won't ever overwrite a jQuery native method?

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?


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.


You would probably want to do this in a similar way to regular JavaScript programming a getElementsByClassName function - you check if it exists and create it if not.


A slightly better (performance-wise) version:

jQuery.fn.foo || (jQuery.fn.foo = function(){
var $ = jQuery;
(your code goes here)
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜