Reputation: 720
this is very confused me, and here is my simple html file:
<html>
<head>
</head>
<body>
<div id="misc">Test</div>
</body>
</html>
in Firebug console: I have this script:
var c = document.documentElement.childNodes[2].childNodes[3];
alert(c.id); //Return misc
alert(c.constructor); // Return [object HTMLDivElement]
As far as I know, a constructor of a function is a function (which is also a object but I'm not talking about that Function Object here). Now c's constructor is a object, and if I ask c'constructor constructor (which is c.constructor.constructor), It'll now return a "real" function, like this:
function Object() {
[native code]
}
I don't know why c.constructor is an object ( [object HTMLDivElement] ), it should be a function as expected. Could you help me understand this one? Thank you!
Upvotes: 0
Views: 180
Reputation: 113896
The short answer is: c
does not have a regular constructor.
The longer answer: native objects like DOM elements, Function objects, the global object (usually window
in browsers), the innerHTML function, etc. don't have regular constructors. This is because they are usually not implemented in JavaScript but at a lower level (in whatever language the browser or interpreter was written in).
The JavaScript language specification allows this - native built-in objects do not have to be normal javascript objects. The real reason is historical -- the specs were written by basically reverse engineering Netscape Navigator and having all the contributors agree on what was written. Since then everyone just stuck to it for backwards compatibility. The practical reason usually given these days is performance: if browsers are allowed to do this then they can be faster since native objects need not carry the heavy baggage of normal JavaScript objects.
In your specific case, DOM elements don't have regular constructors. There are 2 ways you can "construct" DOM objects:
document.createElement()
. This is the official DOM method for creating <div>
s, <span>
s etc. In most browsers this method is not a normal constructor since DOM elements don't normally inherit form its prototype.
innerHTML()
. This is a thin interface to access the browser's HTML compiler. It's the same compiler that the browser uses to parse regular web pages. Again, this is in no way a regular constructor since it doesn't even return the object(s) it creates.
Since DOM elements don't have normal constructors, browsers may return anything for their constructor
property including nothing at all. What you are seeing in your case is mostly left over implementation detail that have leaked through to the javascript engine. It's not something you're supposed to access or use. Much less depend on to develop applications.
Upvotes: 3