Newby Coder header banner

Javascript Objects


An object is a collection of related data and/or functionality (which usually consists of several variables and functions — which are called properties and methods when they are inside objects)

An empty object can be initialized using curly braces {}

var user = {};

An object is made up of one or more members, each of which has a name and a value

A name and value are separated by a colon, and each name-value pair must be separated by a comma

Syntax
var objectName = {
  member1Name: member1Value,
  member2Name: member2Value,
  member3Name: member3Value
};

An object like above is referred to as an object literal in contrast to objects instantiated from classes

Following example creates an object and assigns to user variable

var user = {
  name: {first: 'Jim', title:'Kurosaki'},
  age: 21,
  company: 'Camper',
  email: '[email protected]',
  about: function() {
    alert(this.name.first + ' ' + this.name.title + ' from ' + this.company );
  },
  adult: function() {
    return this.age >= 18;
  }
};

This shows that an object can have another object as member ( name above)

After creating object, its methods and properties can be accessed using Dot . notation

user.name.first
user.age
user.email
user.about()
user.adult()

Getting object members

Dot notation

dot notation involves using . (dot or period) to access properties and methods of an object

The object name (user) is written first followed by a dot

Next comes the property of method to be accessed

user.name.first
user.email
user.adult()

Bracket notation

There is another way to access object properties — using bracket notation

Instead of using

user.age
user.name.first

Following can be used

user['age']
user['name']['first']

Setting object members

To set (update) value of object members, dot or bracket notation can be used like a declaration statement

user.age = 45;
user['name']['last'] = 'Cratchit';

Similarly, new object members can also be created

user['eyes'] = 'hazel';
user.farewell = function() { alert("Bye everybody!"); }

What is this

this keyword refers to current object inside which code is being written

So ,in provided example this is equivalent to user object (i.e. value of user variable)

function() {
    alert(this.name.first + ' ' + this.name.title + ' from ' + this.company );
  }

If value of a member of user object is changed, then using this returns updated value