Answers

Question and Answer:

  Home  Front End Developer (AngularJS)

⟩ 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) {

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.

 269 views

More Questions for you: