JavaScript中的Object.prototype [英] Object.prototype in JavaScript

查看:101
本文介绍了JavaScript中的Object.prototype的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些JavaScript代码定义了一个函数 getElementsByAttribute ,如下所示:

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

这适用于我测试过的所有浏览器,Internet Explorer 7除外(和可能更低) - 这些浏览器抛出对象不支持此属性或方法。

我唯一可以想到的是它不喜欢它是我定义时已经创建了对象原型函数...

将函数定义为......好吧,一个普通函数并将元素作为参数传递,是否有任何方法可以在IE7及以下版本中使用?

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元素不是普通的Javascript对象,也不像你期望的那样继承原型。

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 /

这篇关于JavaScript中的Object.prototype的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆