I am writing my first jQuery plugin, and I'm not entirely sure what should be inside the extension declaration and what shouldn't.
$.fn.myplugin = function () {
var somevar = this;
someFunc(somevar);
};
function someFunc() {/*doSomethin'*/};
OR
$.fn.myplugin = function () {
var somevar = this;
someFunc(somevar);
function someFunc() {/*doSomethin'*/};
};
I'd use the first option because:
It doesn't have any negative side effects.
That's where you are wrong. If you are working with different libraries you risk overwriting someone elses someFunc(), possibly breaking whatever they were trying to do for you. A safer way would be to wrap a closure around your code.
(function(){
$.fn.myplugin = function () {
var somevar = this;
someFunc(somevar);
};
function someFunc() {/*doSomethin'*/};
/* Do whatever other things you need someFunc/myplugin for */
})();
This way your someFunc is shielded from the global namespace.
Alternatively what you might be looking to do is to expose the method of the object to the outside world. Take following example:
$.fn.dog = function () {
this.bark = function() {alert("Woof");};
return this;
};
var $max = new $('#myDogMax').dog();
$max.bark();
This keeps the function within the context of your object but makes it possible to access it cleanly from the outside. Although this usually means that the method is somehow related to the object. It would make little sense to write a bark() function globally, as it are usually dogs that tend do it and not browser windows.
In your first method, you end up polluting the global scope adding someFunc()
. The second method doesn't.
However, that doesn't automatically mean the second method is better. If you enclose the first method in a closure, it basically ends up being the exact same thing, and comes down to personal preference.
Here, it might even be better to use the first method (in a closure), so that if you have multiple jQuery extensions in a single JS file, they can share this base function.
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