joshcomley
joshcomley

Reputation: 28818

Why can I not pass this function in javascript?

I am unable to pass document.getElementById as an argument:

Given this HTML:

<div id="el"></div>

And this javascript:

var test = function(fn) {
  alert(fn("el"));
}
// This works
test(function(id){
  return document.getElementById(id);
});
// This fails
test(document.getElementById);

Fiddle:
https://jsfiddle.net/joshcomley/tv7chn9q/

I get an "Uncaught TypeError: Illegal invocation" in Chrome, for example.

Why is this so?

Upvotes: 0

Views: 60

Answers (2)

Quentin
Quentin

Reputation: 943634

Take this example.

var item = "This is a global variable";

var thing = {
  item: "a value",
  findInThing: function(prop) {
    return this[prop];
  }
}

alert(thing.findInThing("item"));

function call(a_func) {
    return a_func("item"); 
}

alert(call(thing.findInThing));

The value of this inside a function depends on the context in which is is called.

You are calling getElementById after detaching it from the context of document.

It isn't being involved with a DOM document to find the element in, so it fails.

You can create a new function which wraps around another one and then calls it in a specific context using bind:

var myGEBI = document.getElementById.bind(document);
test(myGEBI);

Upvotes: 2

jcubic
jcubic

Reputation: 66560

document.getElementById need to be executed with document as context you can fix that using bind:

test(document.getElementById.bind(document));

FIDDLE

Upvotes: 1

Related Questions