Front End Developer (AngularJS) Question:
Download Questions PDF

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


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

function Person(name) { = name;
Person.prototype.walk = function() {
console.debug( + " 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) Interview Questions And Answers PDF

Previous QuestionNext Question
Explain difference between == and ===?Explain me when would you use GET and POST requests?