Today I am staying out of the philosophical discussion about whether JavaScript is truly an object-oriented language. FYI a lot of that discussion revolves around polymorphism and that because it is not strongly typed it does not have overload methods. That is true of other languages too, consider Groovy. But for the moment, let's just say that if we can actually create objects with properties then we can do some OOP with it.
In this article I am only interested in the tools that JavaScript has to build objects, and JavaScript is a bit schizophrenic about that. For example JavaScript defines the "new" operator so that creating an object looks more like programming Java. But we can also create objects literally or by using the grandparent of all objects: Object.
Let's take a tour of object creation and see if we can sort some all it out. First of all, we can define literal objects and properties using a comma-separated list of "name: value" pairs enclosed in braces. The property names should follow the identifier rules for JavaScript, and the value can be anything: a string, a number, an array, a reference to another object, or even a function. We can save a reference to the new object in a variable, and we can retrieve or assign new values to a property using the the variable and the . (dot) operator:
newline = '<br />';
Box = { width: 4, height: 5 };
document.write('The box is ' + Box.width + ' x ' + Box.height + newline);
document.write('The box volume is ' + (Box.width * Box.height) + newline);
Secondly, by default all JavaScript objects are extensible; all you have to do is assign a value to a new property and the object has it:
Box.depth = 6;
document.write('The box is ' + Box.width + ' x ' + Box.height + ' x ' + Box.depth + newline);
document.write('The box volume is ' + (Box.width * Box.height * Box.depth) + newline);
So, back to that
new operator. It works with a function and builds a new object:
function Rectangle() {
}
var shape = new Rectangle();