2011-02-06 37 views
6

可能重复:
JavaScript function aliasing doesn't seem to workJavaScript的:通过局部变量引用主机功能

为什么不这项工作?

function foo() { 

    var g = document.getElementById; 

    g('sampleID'); 

} 

这个错误被抛出在Chrome:Uncaught TypeError: Illegal invocation
...并在Firefox:Error: uncaught exception: [Exception... "Illegal operation on WrappedNative prototype object"

它工作在IE9测试版虽然!!

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

+0

可能重复[JavaScript函数混淆似乎并没有工作(HTTP://计算器。 com/questions/1007340/javascript-function-aliasing-doesnt-seem-to-work) – 2011-02-06 23:13:37

+0

你有没有试过,`g.call(document,'sampleID');`? – Pointy 2011-02-06 23:16:26

回答

5

大多数浏览器需要将document.getElementById方法被称为在原始对象(document)的上下文中。因此,这会工作:

function foo() {  
    var g = document.getElementById;  
    g.call(document, 'sampleID'); 
} 

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

你也可以使用Function.prototype.bind,以支持它或您所提供的compatibility implementation浏览器:的

function foo() {  
    var g = document.getElementById.bind(document);  
    g('sampleID'); 
}