Ankur Marwaha
Ankur Marwaha

Reputation: 1885

Can I add a method on es6 class after it is defined?

Method

method() {}

function

function func() {}

Above is just to elaborate difference between method and function.

class Student {
  constructor(name, age) {
    this.name = name;
    this.age = age;  
  }
  method1(){}
}

In the above class, after writing the definition. I want to add a method2 to the class, similar to the way method1 is there. I can add a function like soo

Student.prototype.func = function(){...}

But I do not have a way to add a method on the same class. and inside function I will not be able to use super as that is just available inside the method.

  1. Is there a way I can add method after the class is defined ?
  2. So that I will be able to use super inside that.

Upvotes: 1

Views: 2532

Answers (2)

jfriend00
jfriend00

Reputation: 708046

As has already been explained, you can only use super() inside the regular class definition. But, long before we had ES6, we were calling parent method implementations manually. It can be done using the parent's prototype:

class Person {
    talk() {
       // some implementation here
    }
}

class Student extends Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;  
  }
}

Student.prototype.talk = function(data) {
   // now call base method manually
   Person.prototype.talk.call(this, data);
   // then do our extra work
   log(data);
}

Of course, normally you could just declare all your methods within the class declaration so this would not be something you would normally need to do.

Upvotes: 2

loganfsmyth
loganfsmyth

Reputation: 161627

Your snippet adding a new property to the prototype is only approach for adding a function later. One main difference in this case is that simple assignment like that will create the property as enumerable by default, whereas class syntax would create is as non-enumerable. You could use

Object.defineProperty(Student.prototype, "func", {
  configurable: true,
  writable: true,
  value: function() {

  },
});

to address that at least.

Unfortunately as you've seen, adding things to the prototype afterward does not allow usage of super.foo. There is no way for this to be supported, because the behavior of super is based specifically on the lexical nesting of the method syntax method(){} being inside of the class syntax. Methods added programmatically later on would have no way to know which prototype is the "super" one.

Upvotes: 1

Related Questions