Front End Developer (AngularJS) Question:
Download Job Interview Questions and Answers PDF
How can you add a method to a class already defined?
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.
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) Interview Questions And Answers
PDF
Previous Question | Next Question |
Explain difference between == and ===? | Explain me when would you use GET and POST requests? |