Assigning document.getElementById to another function

I am trying to do the following in JavaScript:

var gete = document.getElementById; 

But I get the following error (from FireBug 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 why do I get the exception above when assigning a function to a different name?

+3
source share
3 answers

To call the alias document.getElementById in Firefox and Google Chrome, you must do it like this:

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

For a detailed explanation of this issue, you can check out the following post:

+5
source

ECMAScript 5 introduces the bind() function, which binds the function to an object so that it can be called directly without using 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.

+4
source

You can link or call or apply if you want, or you can directly assign a function, as you noticed -

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

But why not improve it a little bit, but what to use?

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

Source: https://habr.com/ru/post/1310780/


All Articles