覆盖原生函数? [英] Overriding native function?

查看:70
本文介绍了覆盖原生函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

本地 document.createElement()是愚蠢的(它只需要一个标签名称,没有属性)。我怎么不能覆盖它?这怎么不行?

The native document.createElement() is silly-stupid (it takes only a tag name and no attributes). How come I can't override it? How come this doesn't work?

var originalFunction = document.createElement;

document.createElement = function(tag, attributes) {
    var element = originalFunction(tag);

    if (attributes) {
        for (var attribute in attributes) {
            element.setAttribute(attribute, attributes[attribute]);
        }
    }

    return element;
};

问题是当您尝试替换本机功能时,浏览器会炸毁。由于文档不是JavaScript原语,所以您也不能为其创建原型。 WTF。

The problem is that browsers blow up when you try to replace a native function. Since document is not a JavaScript primitive, you can't create a prototype for it either. WTF.

推荐答案

据我所知,问题是调用code> document.createElement ()函数,即使引用必须来自文档。所以修改你的代码:

As far as I can tell the problem is that a call to the document.createElement() function even when referenced has to be from the document. So modify your code:

var element = originalFunction.call(document, tag);

这篇关于覆盖原生函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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