While I’m at work, I’ll write little snippets of JS to explore the language proper, not using any frameworks. However, since I’m lazy, I’ll keep a reference to document.getElementById by storing it in a variable:
var grab = document.getElementById;
var foo = grab('some_id');
var bar = grab('some_other_id');
This has always worked in IE7/8, but I tried it back home on Firefox and it didn’t like the shortcut. Now, it works when I wrap it up in a function and close over the argument:
var grab = function (some_id) {
return document.getElementById(some_id);
};
but I don’t understand why I need to do that; in Firefox I can throw around references to user-defined functions and it doesn’t complain:
var foo = function(x) {
alert(x);
};
var bar = foo;
foo('foo'); // alerts 'foo'
bar('bar'); // alerts 'bar'
Why can’t I call a reference to document.getElementById I’ve stored in a variable?
It’s about
thisvalue. I’ve created a test case on jsFiddle http://jsfiddle.net/pomeh/mPRZR/ to show you the problem.When you do
var foo = document.getElementById("...");, this value ofthisinside the function is thedocumentobject.When you do
var grab = document.getElementById; var foo = grab("...");you’re executing thegetElementByIdin a global context. In this case, the value ofthisinside the function is the global object, and not thedocumentobject.I hope that’s clear for you 🙂 Look at the example and logged values.