Alex Rivera | Logout

JavaScript function aliasing doesn't seem to work

Asked 2009-06-17T14:20:09.153
91

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">

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 (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".

Am I doing something wrong? Can anyone else reproduce this?

Also, oddly enough, I just tried and it works in IE8.

Edit
Report

1 Answer

2

Another short answer, just for wrapping/aliasing console.log and similar logging methods. They all expect to be in the console context.

This is usable when wrapping console.log with some fallbacks, in case you or your users have run into trouble when using a browser that doesn't (always) support it. This is not a full solution to that problem though, as it needs to be expanded checks and a fallback - your mileage may vary.

Example using warnings

var warn = function(){ console.warn.apply(console, arguments); }

Then use it as usual

warn("I need to debug a number and an object", 9999, { "user" : "Joel" });

If you prefer to see your logging arguments wrapped in an array (I do, most of the time), substitute .apply(...) with .call(...).

Should work with console.log(), console.debug(), console.info(), console.warn(), console.error(). See also console on MDN.

answered 2012-02-03T10:06:34.433

Your Answer