Learn Simpli

Free Online Tutorial For Programmers, Contains a Solution For Question in Programming. Quizzes and Practice / Company / Test interview Questions.

new operator and function constructor in Javascript

Constructor function
  1. The constructor function can be created with a new keyword
  2. When a new operator is used to create a function the following things happen
How it works
  1. The new empty object is created
  2. The function is called and this keyword is set
  3. An empty object is linked to a prototype
  4. The function returns the empty object
let Employee = function (name, department) {
    console.log(this);
    this.name = name;
    this.department = department;
    console.log(this);
}

let john = new Employee('John', 'Software');
console.log(john);
// Employee {}
// Employee { name: 'John', department: 'Software' }
// Employee { name: 'John', department: 'Software' }