Front End Developer (AngularJS) Question:

How can you add a method to a class already defined?

Tweet Share WhatsApp

Answer:

You can add a new method to a javascript class using prototype:

function Person(name) {
this.name = name;
}
Person.prototype.walk = function() {
console.debug(this.name + " is walking.");
}
// Calling the new method
var person = new Person("Hussain");
person.walk(); // "Hussain is walking."
It's worth mentioning that adding methods via prototype is the most inexpensive way in terms of performance since the method is tied to the prototype of the class. It means, for every new instance of class Person, you will have access to the prototype's walk() method. Now, if you declare walk() method inside the Person class, you will end up recreating the method for every new instance of Person.

Download Front End Developer (AngularJS) PDF Read All 62 Front End Developer (AngularJS) Questions
Previous QuestionNext Question
Explain difference between == and ===?Explain me when would you use GET and POST requests?