β± 0:00est. 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.