Object Oriented

Class

JavaScript

 

Defining Class (Constructor Functions)

ECMAScript 5
function Person(name, age) {
  
  this.name = name;
  this.age = age;
  
  this.greet = function() {
    console.log("Hi! I'm " + this.name);
  };
  
}

JavaScript is a prototype-based language, so in order to use Object Oriented concepts and practices, you need to mimic them.

JavaScript uses special functions called Constructor Functions to define and initialize objects and their features.

The Constructor Function is JavaScript's version of a Class concept.

this keyword inside a Constructor Function is going to be a reference to the Person object whenever a new intance of it is being created.

 

Defining Class (ES6)

ECMAScript 2015
class Person {

  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  greet() {
    console.log("Hi! I'm " + this.name);
  }

}

Classes defined by keyword class are primarily syntactical sugar and it doesn't introduce a new object-oriented inheritance model to JavaScript.

 

Instantiate Class

ECMAScript 5
var person1 = new Person('Bob', 25);

var person2 = new Person('Sarah', 21);

new keyword creates a new object by following the steps below:

  1. Creates a new object.
  2. Assigns this to the created object.
  3. Calls the function with the parameters specified.
  4. In the end, returns this.
 

Object Literals

ECMAScript 5
var person1 = {
  name: 'Bob',
  age: 25,
  greet: function() {
    console.log("Hi! I'm " + person1.name);
  }
}

If you want to create your objects directly without defining a Class, you can use Object Literals.

Object literals are handy when you want to create your objects pretty quick but they are limited to what they are.