Javascript:如何创建全局函数和变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5053292/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript : How to create global functions & variables
提问by Adam
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?
因为这仅适用于该元素,但是我应该如何创建全局函数,我可以在所有元素(例如 JavaScript 内置的元素)上使用该函数?
回答by Richard H
Use Element's prototype to extend its functionality:
使用 Element 的原型扩展其功能:
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.
编辑:我刚刚快速检查了一下,似乎这不适用于 IE7 及更低版本,而 IE8 可能有问题。
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:
编辑 2:正如 Eli 指出的那样,扩展您不拥有的对象可能不是最佳实践。鉴于这个和不稳定的 IE 支持,您可能需要考虑一个简单的过程函数:
function myFunction(element) {
// your code...
// which may or may not return an object or value
return blah;
}
回答by Eli
See this question: In Javascript, can you extend the DOM?.
看到这个问题:在Javascript中,你能扩展DOM吗?.
While it is possible to do, its generally considered bad practice to change the functionality of objects you don't own.
虽然可以这样做,但通常认为更改不属于您的对象的功能是不好的做法。
回答by Zimbabao
Try
尝试
Object.prototype.myNeweFunction=function(){
doSomthing..
}
回答by Free Consulting
For example:
例如:
HTMLAnchorElement.prototype.click = function () {
alert('HAI!');
};
document.links[0].click();
Figure out right object to extend by querying document.getElementById("element").constructor
通过查询找出要扩展的正确对象 document.getElementById("element").constructor
回答by jpsimons
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.
Prototype(库)执行此操作,通过向其原型添加方法来扩展本机(内置)DomElement 类。它在旧的 IE 中不起作用,所以我建议不要使用它。