代码之家  ›  专栏  ›  技术社区  ›  Andreas Grech

将document.getElementByID分配给另一个函数

  •  3
  • Andreas Grech  · 技术社区  · 16 年前

    我尝试在javascript中执行以下操作:

    var gete = document.getElementById;
    

    但我(从Firebug的控制台)得到以下错误:

    uncaught exception: [Exception... "Illegal operation on WrappedNative prototype object" nsresult: "0x8057000c (NS_ERROR_XPC_BAD_OP_ON_WN_PROTO)" location: "JS frame :: http://localhost:8080/im_ass1/ :: anonymous :: line 15" data: no ]

    很明显,我可以将函数包装如下:

    var gete = function (id) {
        return document.getElementById(id);
    };
    

    但是,当将函数赋给另一个名称时,我得到上述异常的原因是什么?

    3 回复  |  直到 8 年前
        1
  •  5
  •   Community Mohan Dere    9 年前

    调用的别名 document.getElementById 在firefox和google chrome中,您应该这样做:

    var gete = document.getElementById;
    gete.call(document, 'header').innerHTML = 'new';
    

    您可能需要查看下面的堆栈溢出日志,以获得背后的详细解释:

        2
  •  4
  •   Alex Jasmin    8 年前

    ECMAScript 5介绍了 bind() 将函数与对象绑定,以便可以直接调用该函数而不必使用 func.call(thisObj) 每次通话。

    var func = document.getElementById.bind(document);
    func("foo");  // We don't have to use func.call(doument, "foo")
    

    小精灵 Prototype 然后被添加到语言中。

        3
  •  1
  •   Daniel Vassallo    16 年前

    您可以根据需要绑定、调用或应用,也可以直接分配函数, 正如你所观察到的-

    var gete= function(s){return document.getElementById(s)}
    

    但是为什么不稍微改进一下,或者有什么用呢?

    var gete= function(s){return s && s.nodeType==1? s: document.getElementById(s)}