getElementById
is a method that needs a context (this
) set to document
to work as expected.
One way is to call it using
fn = document.getElementById;
fn.call(document, 'some-id');
or you can use ES5 fumction bind
(which will fix the context) like this:
fn = document.getElementById.bind(document);
fn('some-id');
or you can do what bind
does in the end by yourself:
fn = function (id) {
return document.getElementById(id);
};
fn('some-id');
JavaScript is quite different in its handling of methods as regular functions and supplying the calling context for a method very dynamically. You can even override this
by using call
or apply
methods of the functions themselves (even function is an object that has methods, these inherited from Function.prototype).