JavaScript函数别名似乎不工作 [英] JavaScript function aliasing doesn't seem to work
问题描述
我只是在阅读这个问题,想尝试别名方法,而不是函数包装器方法,但我似乎无法使它工作在Firefox 3或3.5beta4或谷歌Chrome,无论是在他们的调试窗口和测试网页。
I was just reading this question and wanted to try the alias method rather than the function-wrapper method, but I couldn't seem to get it to work in either Firefox 3 or 3.5beta4, or Google Chrome, both in their debug windows and in a test web page.
Firebug:
>>> window.myAlias = document.getElementById
function()
>>> myAlias('item1')
>>> window.myAlias('item1')
>>> document.getElementById('item1')
<div id="item1">
如果我把它放在网页中,调用myAlias会给我这个错误:
If I put it in a web page, the call to myAlias gives me this error:
uncaught exception: [Exception... "Illegal operation on WrappedNative prototype object" nsresult: "0x8057000c (NS_ERROR_XPC_BAD_OP_ON_WN_PROTO)" location: "JS frame :: file:///[...snip...]/test.html :: <TOP_LEVEL> :: line 7" data: no]
Chrome(为了清楚起见,插入了>>>):
Chrome (with >>>'s inserted for clarity):
>>> window.myAlias = document.getElementById
function getElementById() { [native code] }
>>> window.myAlias('item1')
TypeError: Illegal invocation
>>> document.getElementById('item1')
<div id=?"item1">?
在测试页面中,我得到了相同的非法调用。
And in the test page, I get the same "Illegal invocation".
我做错了什么?
此外,奇怪的是,我只是试过,它在IE8中工作。
Also, oddly enough, I just tried and it works in IE8.
推荐答案
您必须将该方法绑定到文档对象。看:
You have to bind that method to the document object. Look:
>>> $ = document.getElementById
getElementById()
>>> $('bn_home')
[Exception... "Cannot modify properties of a WrappedNative" ... anonymous :: line 72 data: no]
>>> $.call(document, 'bn_home')
<body id="bn_home" onload="init();">
当你做一个简单的别名时,函数会在全局对象上调用,而不是在文档对象。使用一种名为closures的技术来解决这个问题:
When you’re doing a simple alias, the function is called on the global object, not on the document object. Use a technique called closures to fix this:
function makeAlias(object, name) {
var fn = object ? object[name] : null;
if (typeof fn == 'undefined') return function () {}
return function () {
return fn.apply(object, arguments)
}
}
$ = makeAlias(document, 'getElementById');
>>> $('bn_home')
<body id="bn_home" onload="init();">
这样就不会丢失对原始对象的引用。
This way you don’t loose the reference to the original object.
在2012年,有一个新的 bind
方法从ES5允许我们以一个鸽友的方式:
In 2012, there is the new bind
method from ES5 that allows us to do this in a fancier way:
>>> $ = document.getElementById.bind(document)
>>> $('bn_home')
<body id="bn_home" onload="init();">
这篇关于JavaScript函数别名似乎不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!