Constructors

In OOP constructor is a special method that creates and initializes an object.

The new operator allows to call function as constructor.

The keyword constructor is used in class syntax (ES6+) for defining a constructor.

class Person{
  constructor(fName, lName){
    var self = this;
    this.firstName = fName;
    this.lastName = lName;
  }

  getFullName(){
    return this.firstName + " " + this.lastName;
  }  
}

var johnSmith = new Person("John", "Smith");

console.log("johnSmith=", johnSmith  );
console.log("full name is ", johnSmith.getFullName() );
function Person(fName, lName){
  var self = this; 
  this.firstName = fName;
  this.lastName = lName;
  this.getFullName = function () {
    return self.firstName + " " + self.lastName;
  }
}

var johnSmith = new Person("John", "Smith");

console.log("johnSmith=", johnSmith  );
console.log("first name is ", johnSmith.firstName );