简体   繁体   中英

Object.prototype in JavaScript

I have some JavaScript code that defines a function getElementsByAttribute as follows:

Object.prototype.getElementsByAttribute = function(attr) {
    var children = this.all || this.getElementsByTagName('*'),
        ret = [], i, c;
        for( i=0; i<children.length; i++) {
            c = children[i].getAttribute(attr);
            if( typeof c == "string" && c != "")
                ret.push(children[i]);
        }
    return ret;
}

This works in all browsers I have tested in, except Internet Explorer 7 (and presumably lower) - these browers throw "Object doesn't support this property or method."
The only thing I can think of that it doesn't like that is the Objects have already been created when I defined the prototype function...
Shrot of defining the function as a... well, a "normal" function and passing the element as an argument, is there any way to make this work in IE7 and below?

IE DOM elements aren't normal Javascript objects and do not inherit prototypes as you would expect.

http://perfectionkills.com/whats-wrong-with-extending-the-dom/

Adding things to Object.prototype is a really bad idea. It will be added to every object, and that will cause unintended behavior, I guarantee it.

Simply define your function and decorate it onto whatever objects you need dynamically.

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