Object Oriented

Special Method

JavaScript

 

Constructor

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

Constructor is the first routine that executes when you create an object from a Class.

Here the body of Person function (representing the class Person) acts as a constructor.

So as soon as you create an object using new Person(), the body of the Person function is going to be called.

Notice here that, the greet is being defined on object in instantiations, but in practice, methods are being defined on the prototype. This way the method is already defined before your new object gets created.

function Person(name, age) {
  this.name = name;
  this.age = age;
}

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

To learn more about prototype and Inheritence in JavaScript, checkout the Inheritence topic.

 

Constructor (ES6)

ECMAScript 5
class Person {
  
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  
}

In ES6 class syntax, constructor is the first method that is being executed when new object gets created.

 

Getter

ECMAScript 2015
class Person {

  // ...
  
  get fullname() {
    return this.fname + " " + this.lname;
  }
  
}

You can define Getters using get keyword.

If a getter method is defined, it is called whenever its name is tried to be read on an object using . operator, similar to reading a value of a property.

var person1 = new Person();
person1.fname = "Sam";
person1.lname = "Winchester";

var fullname = person1.fullname; // Sam Winchester

Getter is an ES5 feature, but it's more readable to write it in ES6 class syntax rather than Function Constructors.

You can define Getters using Object.defineProperty() as well.

 

Setter

ECMAScript 2015
class Person {

  // ...
  
  set fullname(str) {
    var names = str.split(' ');
    
    this.fname = names[0];
    this.lname = names[1];
  }
  
}

You can define Getters using set keyword.

If a setter method is defined, it is called whenever its name is tried to be set on an object using . operator, similar to setting a value for a property.

var person1 = new Person();
person1.fullname = "Sam Winchester";

var firstname = person1.fname;  // Sam
var lastname = person1.lname;   // Winchester

Setter is an ES5 feature, but it's more readable to write it in ES6 class syntax rather than Function Constructors.

You can define Getters using Object.defineProperty() as well.