Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/405.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将document.getElementById分配给另一个函数_Javascript_First Class Functions - Fatal编程技术网

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

Javascript 将document.getElementById分配给另一个函数,javascript,first-class-functions,Javascript,First Class Functions,我正在尝试使用JavaScript执行以下操作: var gete = document.getElementById; 但我(从FireBug的控制台)收到以下错误: uncaught exception:[exception…”“WrappedNative prototype对象上的非法操作”nsresult:“0x8057000c(NS_ERROR\u XPC\u BAD\u OP_on_WN_PROTO)”位置:“JS frame::http://localhost:8080/im_a

我正在尝试使用JavaScript执行以下操作:

var gete = document.getElementById;
但我(从FireBug的控制台)收到以下错误:

uncaught exception:[exception…”“WrappedNative prototype对象上的非法操作”nsresult:“0x8057000c(NS_ERROR\u XPC\u BAD\u OP_on_WN_PROTO)”位置:“JS frame::http://localhost:8080/im_ass1/ ::匿名::第15行“数据:否
]

现在,显然我可以将函数包装如下:

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

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

要在Firefox和Google Chrome中调用
document.getElementById
的别名,您应该按照以下步骤执行:

var gete = document.getElementById;
gete.call(document, 'header').innerHTML = 'new';
您可能希望查看以下堆栈溢出帖子,以了解其背后的详细解释:


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

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

bind()
最初在库中提供,后来添加到语言中。

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

var gete= function(s){return document.getElementById(s)}
但是为什么不改进一下,或者有什么用呢

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

您使用的是最新版本的Firefox和Firebug吗?我这样做没有任何错误。我当前的版本是:
3.6.3
@Andreas:很高兴见到一位同胞!:)