JavaScript:通过局部变量引用主机功能

Šim*_*das 6 javascript

可能重复:
JavaScript函数别名似乎不起作用

为什么这不起作用?

function foo() {

    var g = document.getElementById;

    g('sampleID');

} 
Run Code Online (Sandbox Code Playgroud)

在Chrome:Uncaught TypeError: Illegal invocation
...和Firefox中引发此错误:Error: uncaught exception: [Exception... "Illegal operation on WrappedNative prototype object"

它适用于IE9测试版!!

演示: http ://jsfiddle.net/ugBpc/

And*_*y E 5

大多数浏览器都要求document.getElementById在原始对象(document)的上下文中调用该方法.这样可行:

function foo() {      
    var g = document.getElementById;      
    g.call(document, 'sampleID');  
}
Run Code Online (Sandbox Code Playgroud)

但是,这将在Internet Explorer 7及更低版本中失败,因为DOM方法不会从中继承Function.prototype.您的原始示例应适用于所有版本的Internet Explorer.

您也可以Function.prototype.bind在支持它的浏览器或您提供兼容性实现的浏览器中使用:

function foo() {      
    var g = document.getElementById.bind(document);      
    g('sampleID');  
}
Run Code Online (Sandbox Code Playgroud)