Objects

Javascript Objects

JavaScript is an object oriented programming language. In the previous lessons, you learned how to use different types of variables to represent different kinds of data in JavaScript. These variable can have only one value at a time. But Javascript objects can contain multiple values, as well as functions for working with these values. So, these Objects enable you to group related data and the functions into a single entity

An object is a collection of properties and these properties can be either primitives or other objects, including functions. Unlike most other object oriented programming languages, which are based on classes and class instances, JavaScript is based on prototypal inheritance in which objects inherit from other objects. So, these objects make it much easier to manage in your programs

How to create and use objects in Javascript

var student = { name: "Jack", age: 12, getName: function() { alert(this.name); } };

In the above code, student is an Object and name and age are Object properties and getName() is the method in the Object.

Call Object function

student.getName();

The above code will alert - Jack.

Object constructor

Object constructor

An object constructor is normally a regular JavaScript function that creates an object wrapper for the given value.

function studentConstructor() { this.name = "Jack"; this.age = 12; this.getName = function() { alert(this.name); } }

How to create a New Instance from a Constructor

var student = new studentConstructor(); student.getName(); // will alert "Jack"

Literal notation in Javascript Object

var student = { name: "Jack", age: 12, getName: function() { alert(this.name); } }; student.getName(); //will alert "Jack"

Object.create() in Javascript Object

We can create new objects in Javascript using Object.create() method

var student = { name: "Jack", age: 12, getName: function() { alert(this.name); } }; var st = Object.create(student); st.getName();

Accessing Object Properties in JavaScript

We can access Object Properties in JavaScript using either the dot(.) notation or the bracket[] notation.

var student = {}; student.name = "Jack"; // access via . notation student["age"] = 12; // access via [] brackets alert(student["name"]); // will alert "Jack" alert(student.age); // will alert 12 alert(student.name); // will alert "Jack" alert(student["age"]); // will alert 12

Object contain another Object

Object contain another Object

An Object can contain any data, including other objects too. The following example shows how to a Javascript Object contain other Object and access values.

var student = { name: "Jack", age: 12, classTeacher: { firstname: "John", lastname: "Peter" } }; alert(student.classTeacher.firstname); alert(student['classTeacher']['firstname']); alert(student.classTeacher['firstname']); alert(student['classTeacher'].firstname);