When people talk to me about DailyJS they often ask for more beginner's articles. Therefore, we're starting the JS101 series on DailyJS. These are intended to be short guides on fundamental topics that shouldn't take more than about 10 minutes to read.
Object, so what better place to start?
var one = 1 , oneObject = new Number(1); log(one === oneObject); log(typeof(one), typeof(oneObject));
I've made an interactive version of this example that you can experiment with here: http://jsfiddle.net/uWup3/.
This uses the strict equals operator to compare the value
1 with the object
new Number(1), and
false is returned. The reason for this is
1 is a primitive value, and is not an object. The number created with
new Number is an object, as shown by the value returned by
There are other primitive values: Undefined, Null, Boolean, Number, and String. Another interesting point relates to
Undefined and how it's a type whose sole value is
The 'items' in this object --
created -- are known as properties. While it's difficult to imagine breaking down
true into their constituent parts, this object can easily be broken down. Notice how each value can be a different type -- both primitive values and objects can be combined together in an object.
Now consider this:
new Object to create a new instance. According to the language specification, under Object Initialiser, these forms are equivalent -- creating objects with an object literal will return a new object as if
new Object() was used. Similarly, the array literal
['C', 'Java', 'Scheme'] will create a new object as if
new Array() had been called.
The important thing to notice is the use of a constructor. In this case the constructor is
new Object, but there are other built-in constructors. I also sneaked in
new Date which creates a
The previous example looks more like a data record than a reusable piece of code. We can make it more reusable by creating a constructor -- a function that knows how to initialise a certain flavour of object.
Now I can make other programming languages:
var c = new Language( 'Dennis Ritchie' , new Date(1972, 0, 1) , ['B', 'ALGOL'] );
The constructor can be accessed using the
constructor property, like this:
c.constructor. In this case it'll return
Language. Play around with it here: http://jsfiddle.net/zYzER/6/.
In the ES5 specification under Properties of the Object Prototype Object, other properties of objects are mentioned. For example, we also get
toString, and some stranger sounding methods like