Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

JavaScript Add Methods to a Constructor Function Using Prototype

// constructor function
function Person () {
    this.name = 'John',
    this.age = 23
}

// creating objects
const person1 = new Person();
const person2 = new Person();

// adding a method to the constructor function
Person.prototype.greet = function() {
    console.log('hello' + ' ' +  this.name);
}

person1.greet(); // hello John
person2.greet(); // hello John
 
PREVIOUS NEXT
Tagged: #JavaScript #Add #Methods #Constructor #Function #Using #Prototype
ADD COMMENT
Topic
Name
4+6 =