Skip to main content
0:03est. 3 min

Chapter 57- Function Constructors, 'new', and the History of Javascript

Notes

Example 1 : Function constructor
function Person(){ //Constructor
this.firstname = ‘John';
this.lastname = ‘Doe';
}
//Creating new object using "new" keyword
var john = new Person();
console.log(john);
//OUTPUT Person { fistname: "John",lastname: "Doe" }
Explanation - "new" keyword creates an empty object typeof Person and then Person function is invoked, Now this variable is pointing to empty object in memory so this.firstname and this.lastname being added up on empty object. Now js engine returns object created by new keyword.
#Constructor with params
Example 2 :
function Person(firstname, lastname){ //Constructor
console.log(this); // Person {}
this.firstname =firstname;
this.lastname =lastname;
}
var john = new Person(‘John','Doe');
#BIGWORD Function Constructors - A normal function that is used to construct objects. The ‘this' variable points to a new empty object, and that object is returned from the function automatically.