So I’m trying to define a function g() that is like document.getElementById. The following works just fine:
var g = function(id){return document.getElementById(id)};
But why doesn’t this more direct code work?
var g = document.getElementById;
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The problem is that of context. When you fire an object’s function, it is fired with the object as the value of
this(unless you specify otherwise).g = document.getElementByIdputs the functiongetElementByIdinto the variableg, but doesn’t set the context.Therefore, when you run
g(someId), there is no context on which the function can run. It is run with the global objectwindowas the value ofthis, and that doesn’t work. (To be precise, it doesn’t work because you could be operating with anydocumentobject, not justwindow.document, and you haven’t specified one.)You could get around this with
call, where you set the context:However, this isn’t an improvement over the original!