admin管理员组

文章数量:1289830

I am trying to do the following in JavaScript:

var gete = document.getElementById;

But I am getting the following error (From FireBug's Console):

uncaught exception: [Exception... "Illegal operation on WrappedNative prototype object" nsresult: "0x8057000c (NS_ERROR_XPC_BAD_OP_ON_WN_PROTO)" location: "JS frame :: http://localhost:8080/im_ass1/ :: anonymous :: line 15" data: no]

Now obviously I can wrap the function as follows:

var gete = function (id) {
    return document.getElementById(id);
};

But what is the reason I'm getting the above exception when assigning the function to another name?

I am trying to do the following in JavaScript:

var gete = document.getElementById;

But I am getting the following error (From FireBug's Console):

uncaught exception: [Exception... "Illegal operation on WrappedNative prototype object" nsresult: "0x8057000c (NS_ERROR_XPC_BAD_OP_ON_WN_PROTO)" location: "JS frame :: http://localhost:8080/im_ass1/ :: anonymous :: line 15" data: no]

Now obviously I can wrap the function as follows:

var gete = function (id) {
    return document.getElementById(id);
};

But what is the reason I'm getting the above exception when assigning the function to another name?

Share Improve this question asked Apr 16, 2010 at 22:42 Andreas GrechAndreas Grech 108k101 gold badges303 silver badges362 bronze badges 2
  • Are you using the latest version of Firefox and Firebug? I don't get any errors doing this. – Jimmy Commented Apr 16, 2010 at 22:56
  • My current version is: 3.6.3 – Andreas Grech Commented Apr 16, 2010 at 23:19
Add a ment  | 

3 Answers 3

Reset to default 7

ECMAScript 5 introduces the bind() function that binds a function with an object so that it can be called directly without having to use func.call(thisObj) for each call.

var func = document.getElementById.bind(document);
func("foo");  // We don't have to use func.call(doument, "foo")

bind() was first available in the Prototype library and was later added to the language.

To invoke an alias of document.getElementById in Firefox and Google Chrome, you should be doing it as follows:

var gete = document.getElementById;
gete.call(document, 'header').innerHTML = 'new';

You may want to check out the following Stack Overflow post for a detailed explanation behind this:

  • JavaScript function aliasing doesn’t seem to work

You can bind or call or apply if you like, or you can assign the function directly, as you observed-

var gete= function(s){return document.getElementById(s)}

But why not improve it a tad, or what's the use?

var gete= function(s){return s && s.nodeType==1? s: document.getElementById(s)}

本文标签: javascriptAssigning documentgetElementById to another functionStack Overflow