5

I was thinking to minimize some javascript code but I get this "illegal invocation" error when I try to call a function through an alias

var d = document.createElement;
d('input');

Does anybody know why? tx

Elfy
  • 1,733
  • 6
  • 19
  • 39

2 Answers2

9

Looks like this has been addressed by others. It boils down to the fact that

document.createElement checks to make sure that this refers to document. You can bypass this behavior by doing the following:

Either A: always use it as document.createElement(tagname) OR

B

var o = document.createElement
o.call(document, tagname)

C

var d = document.createElement.bind(document); 

(from above answer)

See http://blog.vjeux.com/2011/javascript/hook-document-createelement.html

CollinD
  • 7,304
  • 2
  • 22
  • 45
5

use

var d = document.createElement.bind(document);

to bind the this in your d function to the document object

Jaromanda X
  • 53,868
  • 5
  • 73
  • 87