Object Creation

Description

An object in Javascript is an "unordered collection of properties each of which contains a primitive value, object, or function."

An object is an array of values in no particular order.

Each property or method is identified by a name and mapped to a value.

Javascript objects are like hash tables: a grouping of name-value pairs where the value may be data or a function.

Object Creation

The simplest way to create a custom object is to create a new instance of Object and add properties and methods to it.


var person = new Object();
person.name = "XML";
person.sayName = function(){//from  ww w  .j  a v a2  s.  c  o  m
   console.log(this.name);
};

var tutorial = new Object(); 
tutorial.name = "JavaScript"; 
tutorial.pageSize = 9; 
        
console.log(tutorial.name); //JavaScript
console.log(tutorial.pageSize); //9

The code above generates the following result.

Object Literal

The previous example can be rewritten using object literal notation as follows:


var person = {
    name: "XML",/*  w  w  w . j a v a  2s.  c o  m*/
    sayName: function(){
        console.log(this.name);
    }
};
console.log(person.name);
person.sayName();

var tutorial = {
   name : "JavaScript",
   pageSize : 9 
}; 
       
console.log(tutorial.name); //JavaScript
console.log(tutorial.pageSize); //9

The code above generates the following result.





















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions