2011-02-06 77 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'); 
} 
相關問題