Here are some fun facts for you: JavaScript is not an object oriented language, but almost everything in JavaScript is an object. JavaScript does not have classes, and we can create an object from an object. A function can be used as a constructor, and returns a newly created object. Every object in JavaScript contains a second object called a prototype object.
If you’re coming from a .NET background, the sentences you just read probably don’t make any sense. But these are all true statements about JavaScript. And in this post we will focus on different ways to create objects in BLOCKED SCRIPT
1. Object as literal
2. Creating an object using the new operator and constructors
3. Creating an object using the Object.create() static method
Object creation as literal
The simplest way to create an object is by creating an object using the object literal. We can create a simple object as shown in the listing below:
var foo = {};
foo.prop = "noo";
console.log(foo.prop);
var rectangle = { height: 20, width: 30 };
console.log(rectangle.height);
rectangle.height = 30;
console.log(rectangle.height);
In the above listing, we have created two objects:
1. Object foo does not contain any properties
2. Object rectangle contains two properties: height and width.
3. Properties can be added to an object after creation too. In the above listing, when object foo was created it did not have any properties, so we added a property named “prop” in the foo object.
4. The value of the properties can be modified after the object creation. In the above listing we modified the height property.
We can create a complex object as the object literal as well. Let us say we want to create a student object. This should contain the following properties:
1. Name
2. Age
3. Subject
4. Parents – another object literal with its own properties like name and age.
The complex student object can be created as shown:
var student = {
name: "David",
age: 20,
parents: {
name: 'Mark',
age: 58
}
};
var studentparentage = student.parents.age;
console.log(studentparentage);
As you notice in the above listing, the parents property is an object itself with its own properties. We can add, remove, and access the properties of the object property in the same way we would with the object.
A single object literal creates as many new objects as it appears or being used in the code. To understand this better, let’s take a look at this code snippet:
var fooarr = [];
for (i = 0; i < 10; i++) {
var foo = { val: i };
fooarr.push(foo);
console.log(fooarr[i].val);
}
console.log(fooarr[3].val);
You will notice here that we are creating the object literals inside a loop and pushing the created object to an array. In the above listing, 10 objects were created, demonstrating that a single object literal can create many new objects if it is inside a loop body or being used repeatedly. In the above code listing, the object literal “foo” is repeating 10 times inside the loop and it is creating 10 new objects. To verify this further we are accessing the 4th object created using the object literal outside the loop.
We need to keep this in mind while working with object literals: one single object literal can create as many new objects as number of times it is used.
Creating an object using the new operator or constructor pattern
In the JavaScript we can create the object using the new operator also. When we create an object using the new operator, it is also known as the constructor pattern. When we create an object using the new operator then the new keyword must be followed by a function invocation. In this case function is works as the constructor. In object oriented world constructor is a function used to construct an object. So the invoked function after the new keyword serve as the constructor which constructs the object and returns the constructed object.
Keep in mind that JavaScript does not have classes (up to ECMA 5.0), but it supports special functions called constructors. Just by calling a function after the new operator, we request function to work as a constructor and returns the newly created object. Inside the constructor current object is referred by the this keyword.
To understand it better, let us consider the following listing,
function Rectangle(height, width) {
this.height = height;
this.width = width;
this.area = function () {
returnthis.height * this.width;
};
};
var rec1 = new Rectangle(45, 6);
var rec2 = new Rectangle(8, 7);
var rec1area = rec1.area();
console.log(rec1area);
var rec2area = rec2.area();
console.log(rec2area);
In the above listing,
1. We created a rectangle function
2. Created object using the new keyword.
3. Invoked rectangle function is called after the new keyword, hence it worked as constructor
4. Rectangle constructor returned the created object.
5. Object is referred with this keyword inside the constructor.
If we call rectangle function without the new operator, it will work as normal JavaScript function. Whereas if we call rectangle function after the new operator, it will work as constructor and return the created object.
Everything is good about the above code but with one problem that the area function is redefined for all the objects. Certainly we do not want this and the area function should be shared among the objects.
Object Prototypes
All the objects such as functions in JavaScript contain a prototype object. When we use function as constructor to create object, properties of prototype object get available to the newly created objects. We can solve the above problem of area function getting redefined using the prototype object of the constructor.
function Rectangle(height, width) {
this.height = height;
this.width = width;
}
Rectangle.prototype.area = function () {
returnthis.height * this.width;
};
var rec1 = new Rectangle(45, 6);
var rec2 = new Rectangle(8, 7);
var rec1area = rec1.area();
console.log(rec1area);
var rec2area = rec2.area();
console.log(rec2area);
In above listing we are creating the area function as the property of the Rectangle prototype. Hence it will be available to all new objects without getting redefined.
Keep in mind that every JavaScript object has a second object associated with it called prototype object. Always the first objects inherits the properties of the prototype object.
Object creation using Object.create()
The Object.create() static method was introduced in ECMA Script 5.0. It is used to construct new object. So using the Object.create() a new object can be created as shown in below listing,
var foo = Object.create(Object.prototype,
{ name: { value: 'koo' } });
console.log(foo.name);
Some important points about Object.create() to remember:
1. This method takes two arguments:
a. The first argument is the prototype of the object to be created, and is the required argument
2. The second arguments is the optional argument, and describes new properties of the newly created object
3. The first argument can be null, but in that case the new object will not inherit any properties
4. To create an empty object, you must pass the Object.prototype as the first argument
Let’s say you have an existing object called foo and you want to use foo as a prototype for a new object called koo with the added property of “food”. You can do so by doing this:
var foo = {
name: 'steve',
age: 30
};
var koo = Object.create(foo,
{ subject: { value: 'koo' } });
console.log(koo.name);
console.log(koo.subject);
In the above listing, we have an object named foo, and we’re using foo as the prototype of the object named koo. Koo will inherit the properties of foo and it will have its own additional properties also.
Conclusion
There are a few different ways to create objects in JavaScript, and in this post we focused on three of them. Stay tuned for the second part of this post where we will focus on:
· Inheritance
· Object Properties
· Properties getters and setters
· Enumerating Properties Etc.
I hope you find my posts useful - thanks for reading, and happy coding!