0

As a functional programming language, JavaScript allows statements like

var obj = {
    key: function () {return true;}
};
var fn = obj.key;

Simple enough, but why does this not work?

$ = document.getElementById;

The assignment itself does not throw any errors, but attempting to use the $ function throws Uncaught TypeError: Illegal invocation in Chrome.

twinlakes
  • 9,438
  • 6
  • 31
  • 42
  • possible duplicate of [JavaScript function aliasing doesn't seem to work](http://stackoverflow.com/questions/1007340/javascript-function-aliasing-doesnt-seem-to-work) – Qantas 94 Heavy Dec 24 '13 at 02:07

2 Answers2

2

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).

jJ'
  • 3,038
  • 32
  • 25
0

You have to declare it as a function and specify the parameter(s) you’ll need:

var $ = function(id){
return document.getElementById(id);
};
  • I'm not looking for a solution, I'm asking about the language specifications that prohibit the assigning the getElementById function to a variable – twinlakes Dec 24 '13 at 02:30