Reputation: 7180
I'm wondering how can I attach a function to be available for each object on the page. I know that I can do it like this:
mything = {
init: function(SELECTOR){
},
destroy: function(){
}
};
But then it is available to me only this way: mything.init(SELECTOR);
What I want is to be able to do the same thing this way:
$('.mydiv, input, whatever').myFunction({ 'my' : 'arg', 'my2' : 'arg2' });
$('.mydiv').myFunction('destroy');
I know that there are plenty of Javascript tutorials out there but I don't know how to search for this type of functionality. Any help would be appreciated!
Upvotes: 0
Views: 70
Reputation: 51850
The clean way to do what you describe is to wrap your code inside a jQuery plugin.
Here is the official jquery plugin guide. Read through it, it is actually quite simple to understand.
The part about wrapping functions (so that $(selector).myFunction()
calls init
, $(selector).myFunction('doThis')
calls doThis
, etc...) is here.
Upvotes: 1
Reputation: 95509
This isn't necessarily a great idea (it's a terrible idea), but you can accomplish this with prototypes:
Object.prototype.myFunction = function() {
console.log('Called myFunction');
};
And you can see what happens for an arbitrary object:
document.myFunction();
Note that adding to the prototypes of classes other than your own (and especially the builtin objects or classes belonging to libraries other than your own) can induce lots of confusion. This is one of the reasons why Google's own style guide recommends against this (despite much temptation to add String.startsWith, String.endsWith, and many other useful operations to builtin types).
Upvotes: 2
Reputation: 236022
In your case, it looks like it is just enough for you to extend the jQuery.prototype
.
jQuery.extend( jQuery.fn, mything );
However, it is of course possible, even if not very recommendable, to go that ultimate root and extend the Object.prototype
. This really would add those functions to every and each object.
Upvotes: 4