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

And*_*ech 3 javascript first-class-functions

我试图在JavaScript中执行以下操作:

var gete = document.getElementById;
Run Code Online (Sandbox Code Playgroud)

但是我收到以下错误(来自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);
};
Run Code Online (Sandbox Code Playgroud)

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

Ale*_*min 7

ECMAScript 5引入了bind()将函数与对象绑定的函数,这样就可以直接调用,而不必func.call(thisObj)每次调用都使用。

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

bind()首先在Prototype库中可用,后来添加到该语言中。


Dan*_*llo 5

document.getElementById在Firefox和Google Chrome中调用别名,您应按以下方式执行此操作:

var gete = document.getElementById;
gete.call(document, 'header').innerHTML = 'new';
Run Code Online (Sandbox Code Playgroud)

您可能需要查看以下Stack Overflow帖子,以获取有关此背后的详细说明: