In JavaScript you can create a function in many ways
By using Object Literals
By using new operator
By using Object.create()
Let us explore one by one various options to create object in JavaScript. Very simply you can create an Object using literals
var student = {
name: "dj",
grade: 9,
}
You can create empty object as following. We are creating an object with no properties as below,
var studentempty = {};
A complex object can be created as following. In below code studentinfo property is complex property and taking properties of Student object.
var sportStudent =
{
sports: "cricket",
activeyear: 4,
studentinfo :
{
name: student.name,
grade : student.grade
},
coach : "Mr Singh"
}
Some important points about creating object using object literals are as following,
Object literal is an expression
It creates new object each time it appears in the code
A single object literal can create many objects in loop
Now let us explore that how could we create objects using new operator.
var student = new Object();
var studentArray = new Array();
new operator creates a new object
new operator initialize created object also
new operator invokes a function as give in above code snippet.
Function invoked after new operator is known as Constructor. For all native types JavaScript has predefined constructors.
Other way to create object is by using Object.create() method. You can create object using Object.create() as following ,
var student = Object.create(
{
name: "dj",
grade : 10
}
);
Some important points about Object.create() is as following ,
It is a static function
To use it pass properties like we passed name and grade to create object
When you create object using Object.create() there are always two parameters to this
Prototype
Properties
We will discuss prototype in further posts. And second parameter property (in above code name and grade) we pass to create object.
In these ways you can create object in JavaScript. I hope you find this post useful.
0 comments :
Post a Comment