0
var kk = document.getElementById;
kk("some_id");  // gives Uncaught TypeError: Illegal invocation in chrome

but if we do that same with user defined object it works.

var obj = {
    some_function : function(a){
        alert(a);
    }
};
var kk = obj.some_function;
kk("hello");  // works

what is the reason for this error. i just checked in google chrome and it is not working, i came across this when i was creating a short version for document.getElementById, by var $id = document.getElementById; but it did not work. and one interesting thing is that here $id === document.getElementById; (true) and typeof $id is function.

is that because of some security reasons or something ? sorry for weak english and i m not even good at making good title for questions. thanks for answers.

jbafford
  • 5,528
  • 1
  • 24
  • 37
Tiger
  • 404
  • 1
  • 4
  • 13
  • 1
    Note that while `kk = obj.some_function` works in this case, it may not behave as intended in all cases, eg if `some_function` was making use of the `this` variable. – James Thorpe Jan 15 '16 at 13:08

1 Answers1

0

Use Function.prototype.bind(). It will bind context to document.

var kk = document.getElementById.bind(document);
Moob
  • 14,420
  • 1
  • 34
  • 47
Sergii Shvager
  • 1,226
  • 9
  • 14