简体   繁体   English

Javascript:如何创建全局函数和变量

[英]Javascript : How to create global functions & variables

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内置的元素?

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. 编辑2:同样,Eli指出,扩展您不拥有的对象可能不是最佳做法。 Given this and shaky IE support you might want to consider a simple procedural function: 鉴于这种以及不稳定的IE支持,您可能需要考虑一个简单的过程函数:

function myFunction(element) {
  // your code...

  // which may or may not return an object or value
  return blah;
}

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. 尽管可以这样做,但通常认为改变您不拥有的对象的功能是不好的做法。

Prototype (the library) does this, extends the native (built-in) DomElement class by adding methods to its prototype. Prototype(库)执行此操作,通过向其原型添加方法来扩展本机(内置)DomElement类。 It doesn't work in old IEs though so I'd recommend against it. 它在旧的IE中不起作用,所以我建议反对它。

Try 尝试

Object.prototype.myNeweFunction=function(){
 doSomthing..
}

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来确定要扩展的正确对象

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM