简体   繁体   中英

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?

Use Element's prototype to extend its functionality:

Element.prototype.myNewFunction = function() { 
      // your code...
};

Now you can call this method on any element object.

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可能是不合适的。

Also as Eli points out it's probably not best practice to extend objects you don't own. 同样,Eli指出,扩展您不拥有的对象可能不是最佳做法。 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;
}

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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