⏱ 0:01est. 4 min
Chapter 58- Function Constructors and '.prototype'
Notes
//Function constructor already set the prototype for you.
Example 1 :
//Check following in console
john.__proto__
//OUTPUT Person { }
Functions are special type of objects in javascript
function has name property(optional can be anonymous), code property when we ()invoke it is invocable. Every function has prototype property(used only by new operator).
The prototype property of the function is not the prototype of the function it's the prototype of any objects created if we are using function as the function constructor.
//All functions get special property (prototype)
Example 2 :
function Person(firstname, lastname){ //Constructor
console.log(this); // Person {}
this.firstname =firstname;
this.lastname =lastname;
}
person.prototype.getFullName = function (){
return this.firstname + ‘ ' + this.lastname;
}
var john = new Person(‘John', ‘Doe');
console.log(john);
//OUTPUT
Person { firstname : ‘John', lastname : ‘Doe', getFullName : function }
john.getFullName(); // "John Doe"
//We can add something to our prototype on the fly cuz prototype chain is just looking at these objects at the moment you try to access any one of these methods or properties.
Example 3 :
Person.prototype.getFormalFullName = function (){
return this.lastname + ‘, ‘ + this.firstname;
}
console.log(john.getFormalFullName()); //"Doe, John"