3

Possible Duplicate:
Why can’t I have a direct reference to document.createElement?

I am quite new to Js and have been playing around with it. Since document.getElementById & doucment.createElement is quite long I have decided to put it in a variable; eg var d = document.createElement;

  1. However when I call it like var someElement = d("p"); I get "TypeError: Illegal invocation" and I'm not sure what that means.

  2. If I separate the document object, var d = document; and then give that a property like so: d.e = d.createElement; then use it to create an element someElement = d.e("p") it works.

Can someone explain what causes 1. to fail and why 2. works? Thank you in advance.

Community
  • 1
  • 1
Fee
  • 243
  • 1
  • 9

2 Answers2

0

You need to wrap them in a function so that you can call them from the document object.

var d = function(name) {
    return document.createElement(name);
};

This is simply a requirement of the createElement method implementation. It needs to know what document it should be creating the element from.

When you detach a method from an object, the method has no memory of the original object.

That's why this works:

d.e("p");

Since e is a reference to the createElement method, and it is being called from d, which is a reference to the document, you're effectively doing the same as:

document.createElement("p");
I Hate Lazy
  • 47,415
  • 13
  • 86
  • 77
  • Ok i understand that. I expected core js objects to be special so that thought would have never come to mind. Thank you – Fee Nov 03 '12 at 14:36
0

When you use this notation in JavaScript:

objectName.methodName(arguments)

the method is informed (via the special value this) of the object that you're calling it on. So, when you copy a method from one object to another, it actually becomes a method of the new object.

If you treat a method as just a normal function and copy it to a local variable, and then call it normally:

localVariableNameHoldingMethod(arguments)

then its this will be the global object (window).

ruakh
  • 175,680
  • 26
  • 273
  • 307