Javascript:如何创建全球功能&变量 [英] Javascript : How to create global functions & variables
问题描述
我想创建一个新的函数,可以在元素上使用,比如:
I would like to create a new function what I can use on elements, like:
document.getElementById("element").myNewFunction();
我不是在说这个:
I'm not talking about this:
document.getElementById("element").myNewFunction = function(){
doSomething...
}
因为这只适用于那个元素,但是我应该如何创建全局函数,我可以在所有元素上使用这些元素,比如那些内置到javascript中的元素?
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?
推荐答案
使用Element的原型扩展其功能:
Use Element's prototype to extend its functionality:
Element.prototype.myNewFunction = function() {
// your code...
};
现在您可以在任何元素对象上调用此方法。
Now you can call this method on any element object.
编辑:我刚刚进行了一次快速检查,看起来这不适用于IE7及以下版本,并且IE8可能不适用。
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.
编辑2:另外,正如Eli指出的,扩展不属于自己的对象可能不是最佳做法。鉴于这种IE浏览器的支持,你可能需要考虑一个简单的过程函数:
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;
}
这篇关于Javascript:如何创建全球功能&变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!