CONFESSION: As I found out today not everything is an object. There are also these primitive value types like Undefined, Null, String, Boolean and Number that aren’t objects even though some of them can be represented as an object. This fact doesn’t change any of the stuff written below.
I used to tell myself “Just stay away from the hellish objects and you’ll be fine”.
Well, that was quite naive to say when everything in JS is represented via an object. 🙂
I did some short tests to see.
Object, like the real? one
[code lang=”js”]
var myObject = new Object();
myObject[‘0’] = ‘b’;
myObject[‘1’] = ‘o’;
myObject[‘2’] = ‘o’;
console.log(myObject);
[/code]
I created an object with 3 properties.
The __proto__ thing is an internal property. It points to an object myObject inherits from.
String
[code lang=”js”]
var myString = new String(‘boo’);
console.log(myString);
[/code]
I created a string. As I found out the string is saved into an object.
Each numbered property has the value of one character from the string.
Besides that it has a property length showing the length of the string.
Array
[code lang=”js”]
var myArray = new Array();
myArray[0] = ‘b’;
myArray[1] = ‘o’;
myArray[2] = ‘o’;
console.dir(myArray); // I used console.dir() to get the full object
[/code]
I created an array. The array is once again some type of an object.
The indexed items are basically properties with their values.
Function
[code lang=”js”]
function alertBoo() {
alert(‘boo’);
}
console.dir(alertBoo);
[/code]
It was hard to believe at the first time but yes, a function is an object too.
Each function has a special property called “prototype”. It is used when creating new objects to tell them what their property __proto__ will be. I am not going any further now or my coach will roll his eyes and tell me to rewrite it. 😀
And guess what… the prototype is also an object. 🙂 Hell yeah!