Objects are used to represent the real world entities in our code like bank account, books, person, etc, by storing all relevant information in one place, i.e, an object. We have two ways to create objects in javascript, i.e., 'Literal notation' and 'Constructor functions notation'. You must be thinking what are they and what is the difference between them? Right! Let's start with the object definition :
1. Constructor functions notation : is like a 'template' from which you can create multiple objects.
object definition using constructor function is as follows:
function functionName(){
};
2. Literal Notation : creates a single object. This notation uses curly brackets '{}' and object's properties are defined within the brackets using 'property:value' notation.
object definition using literal notation is as follows:
var ObjName = {
};
Defining Methods and Properties
Terminologies like methods, functions, variables, properties creates confusion. In case of object creation, properties are considered as variables created inside an object and methods are considered as functions created inside an object.
Constructor functions notation:
function Obj(){
this.name = ConstructorObject;
this.work = function(){
alert(this.name);
};
};
While creating an object using constructor notation, each property is prefixed with 'this' keyword, followed by '=' and the value of that property. In case if we have more than one property or method, they are separated by the semicolons.
Literal notation:
var Obj = {
name : LiteralObject,
work : function() {
alert(this.name);
};
};
While creating an object using literal notation, each property has a name, followed by ':' and the value of that property. Here, Obj is an object, name is the property and “LiteralObject” is the value of that property. In case if we have more than one property or method, they are separated by commas.
Accessing properties : we can access the properties in two different ways.
1. dot notation : to access a property, we use “ObjectName.PropertyName”.
2. bracket notation : for accessing the desired property using bracket notation, we use “ObjectName[“PropertyName”]”.
Benefit of using bracket notation is that we can pass the property name as a value to the variable and we can than use that variable to access the property, like:
var Obj = {propertyName : someValue};
var prop = propertyName;
Obj[prop];
we have an Obj object with a property and value, then we have another object prop with value as a property's name. The last line is same as using Obj[“propertyName”].
Let's put all these together
// Create object using constructor notation
var myObject = new Object();
myObject.book = Programming JavaScript;
myObject.language = JavaScript;
//Create another object using literal notation
var myOtherObject = {
book : Web Technology,
language : HTML
};
console.log(myObject.book); // output : Programming JavaScript
console.log(myOtherObject); // output: Web Technology
0 Comment(s)