Why can’t I directly assign document.getElementById to a different function?

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.getElementById puts the function getElementById into the variable g, 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 object window as the value of this, and that doesn’t work. (To be precise, it doesn’t work because you could be operating with any document object, not just window.document, and you haven’t specified one.)

You could get around this with call, where you set the context:

g.call(document, someId);

However, this isn’t an improvement over the original!

Leave a Comment