Javascript : How to create global functions & variables
Solution 1
Use Element's prototype to extend its functionality:
Element.prototype.myNewFunction = function() {
// your code...
};
Now you can call this method on any element object.
Edit: I've just had a quick check around, and it appears that this will not work for IE7 and below, and IE8 might be iffy.
Edit 2: Also as Eli points out it's probably not best practice to extend objects you don't own. Given this and shaky IE support you might want to consider a simple procedural function:
function myFunction(element) {
// your code...
// which may or may not return an object or value
return blah;
}
Solution 2
See this question: In Javascript, can you extend the DOM?.
While it is possible to do, its generally considered bad practice to change the functionality of objects you don't own.
Solution 3
For example:
HTMLAnchorElement.prototype.click = function () {
alert('HAI!');
};
document.links[0].click();
Figure out right object to extend by querying document.getElementById("element").constructor
Solution 4
Try
Object.prototype.myNeweFunction=function(){
doSomthing..
}
Solution 5
Prototype (the library) does this, extends the native (built-in) DomElement class by adding methods to its prototype. It doesn't work in old IEs though so I'd recommend against it.
Adam Halasz
Hi, I made 37 open source node.js projects with +147 million downloads. Created the backend system for Hungary's biggest humor network serving 4.5 million unique monthly visitors with a server cost less than $200/month. Successfully failed with several startups before I turned 20. Making money with tech since I'm 15. Wrote my first HTML page when I was 11. Hacked our first PC when I was 4. Lived in 7 countries in the last 4 years. aimform.com - My company adamhalasz.com - My personal website diet.js - Tiny, fast and modular node.js web framework
Updated on July 26, 2022Comments
-
Adam Halasz almost 2 years
I would like to create a new function that I can use on elements, like this:
document.getElementById("element").myNewFunction();
I'm not talking about this:
document.getElementById("element").myNewFunction = function(){ doSomething... }
Because this works on that element only, but how should I create global function what I can use on all elements like the ones what are built in to JavaScript?
-
Adam Halasz about 13 yearsHmm, element's prototype? so there are prototypes for all kinds of object types? I never really understood how prototypes are working :)
-
Zimbabao about 13 yearsRead javascript.crockford.com/prototypal.html to understand Prototypal inheritance