Hello Duncan,
What you are describing is normal. Here are the behavior, tested on IE6 & FF1.5
- When you use "document.getElementById()", it returns a DOM element as an "object" datatype.
- When you use "new Object()", it returns an "object" datatype.
- When you use "{ foo: 'value', bar: function(){} }", known as "object literal syntax" to declare a class, it returns an "object" datatype.
- When you use "function () { this.foo='value'; this.bar=function(){}; }" to declare a class, it returns a "function" datatype.
(RUN THE "EXAMPLE SCRIPT" AT THE BOTTOM TO SEE THIS IN ACTION)
The above shows the 3 different ways to declare a class. Depending of the way of declaration, the object return different datatype as either "object" or "function". I think it's because of the flexibility in javascript to build a class. You can build a class as an object or as a function.
Using "typeof" to inspect if an object a user-defined class is too generic (well javascript functions are almost all generic anyway). I think you'll need to customize your own class property to check if an user-defined class a class, e.g.,
var myClass = new Object();
myClass.isClass = true;
myClass.foo = 'value';
myClass.bar = function(){};
And use myClass.isClass to verify if it's a class.
<!--- [START] EXAMPLE SCRIPT --->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<body>
<div id="foo">bar</div>
<script type="text/javascript">
// get DOM element
var obj1 = document.getElementById("foo");
alert(typeof obj1); // alert 'object'
// create an Object element
var obj2 = new Object();
obj2.cap = false;
obj2.openMe = function() { cap=true; }
alert(typeof obj2); // alert 'object'
// create an object using the object literal syntax
var obj3 = {
cap: false,
openMe: function(){ cap=true; }
};
alert(typeof obj3); // alert 'object'
// create an object as a function object
var obj4 = function() {
this.cap = false;
this.openMe = function(){ cap=true; }
};
alert(typeof obj4); // alert 'function'
</script>
</body>
</html>
<!--- [END] --->
UserAgent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; (R1 1.5))