Javascript - Object-Oriented Programming

Introduction

JavaScript has no concept of classes, and its objects are different with objects from class-based languages.

JavaScript defines an object as 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 that is mapped to a value.

You can think of JavaScript objects as hash tables: a grouping of name-value pairs where the value may be data or a function.

Each object is created based on a reference type.

Objects

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 = "First";
person.age = 29;
person.job = "writer";
person.sayName = function(){
    console.log(this.name);
};

This example creates an object called person that has three properties: name, age, and job and one method called sayName().

The sayName() method displays the value of this.name, which resolves to person.name.

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

var person = {
    name: "First",
    age: 29,
    job: "writer",
    sayName: function(){
        console.log(this.name);
    }
};