(function($) {
$.fn.myFunction = function(config) {
var defaults = {
setting1: 'myDiv',
setting2: ''
};
var config = $.extend(defaults, config);
//code here
};
})(jQuery)
$(document).ready(function() {
$.fn.myFunction({
setting1: 'myDiv',
setting2: ''
});
});
This is how I’ve been using jQuery plugins, but I recently learned it should be used like:
$('#myDiv').myFunction({
setting1: 'myDiv',
setting2: ''
});
1) I take it this allows the usage of $(this) for $('#myDiv')?
2) Is $(document).ready(function() required?
3) Is there anything detrimental about the way I have been using this jQuery function?
4) If $('#myDiv').myFunction() is the proper usage, how would you call the function if it is simply a function to run at document ready – see my usage here: https://stackoverflow.com/a/12316349/1455709. Is this simply an incorrect usage of the function?
Calling
$.fn.myFunction()and calling$('#myDiv').myFunction()are two different things. There is no right or wrong – it depends upon what you’re doing.Calling $.fn.myFunction()
This is essentially a static function and you can use it like that if you want. In the jQuery world,
.fnis like.prototypeso$.fn.myFunction()is like callingjQuery.prototype.myFunction(). It is allowed, but it’s a static function call that is not associated with a specific jQuery object. If you just want a static function call, then you can do this, but this is not normally how the jQuery prototype is used and I would not generally recommend it. If you just want a static function and want to use the jQuery namespace, you can just do this:and then call it like:
As there is no need to use the prototype at all.
Calling
$('#myDiv').myFunction()The prototype (e.g.
.fnin the jQuery world is used when you want to add methods to actual jQuery objects.When you do this
$('#myDiv').myFunction()is a member function of a live jQuery object. You can refer tothisinside themyFunction()implementation and it will be a jQuery object that, in this case holds the DOM object that corresponds toid="myDiv". If you return the jQuery object from your method, you can also use chaining.Which to Use?
If your code operates on a jQuery object, then it should be a method on a live jQuery object and it should access
thisto get at the jQuery object instance data and you should declare it as$.fn.myFunction = function() {}; and call it as$(‘#myDiv’).myFunction()`.If you code does not operate on jQuery object and is just a utility function that you call and it doesn’t always operate on a jQuery object, then, you should declare it as
$.myFunction = function() {};and you should call it as$.myFunction().