代码之家  ›  专栏  ›  技术社区  ›  Niet the Dark Absol

javascript中的object.prototype

  •  6
  • Niet the Dark Absol  · 技术社区  · 14 年前

    我有一些定义函数的javascript代码 getElementsByAttribute 如下:

    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;
    }
    

    这在我测试过的所有浏览器中都有效,除了InternetExplorer7(可能更低)——这些浏览器抛出“对象不支持此属性或方法”。
    我唯一能想到的是,当我定义原型函数时,对象已经被创建了…
    把函数定义为…好吧,一个“普通”函数,将元素作为参数传递,有没有任何方法可以在IE7和下面实现这个功能?

    2 回复  |  直到 14 年前
        1
  •  6
  •   SLaks    14 年前

    IE DOM元素不是普通的JavaScript对象,并且不会像您期望的那样继承原型。

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

        2
  •  1
  •   Adam Lassek    14 年前

    添加内容到 Object.prototype 是一个 真正地 坏主意。它将被添加到 每一个 对象,这会导致意外的行为,我保证。

    只需定义您的函数并将其装饰到您动态需要的任何对象上。