How to add an method to a class in Javascript ES6

Viewed 37608

I need do add a method to a Javascript class using the new syntax. I tried this way:

class X{

    constructor() {
        this.a = 'b'
    }

    x(){

    }
}

X.prototype.y = function (){
    console.log('y')
}

var x = new X()

x.y()

console.log(X) // print the  the class but not the new method.

It just prints:

class X{

    constructor() {
        this.a = 'b'
    }

    x(){}
}

But I expected

class X{

        constructor() {
            this.a = 'b'
        }

        x(){}

        y(){
            console.log('y');
        }
    }

How could I add a new method to a Javascript class?

4 Answers

I know it's a bit late, but would this have solved your problem back then?

class XWithY extends X {
  constructor() {
    super()
  }
  y() {
    console.log('y')
  }
}

const xwy = new XWithY();

console.log(xwy instanceof X); // outputs true

There are two major ways to add methods to a class, this can be within the scope of the class when writing the code or using ".prototype" to attach a method to your class. Below is an example of adding a method within the class scope:

class Person {
   constructor(fName, lName) {
      this.firstName = fName;
      this.lastName = lName;
   }
   sayName = function() {
   return `My Name is ${this.firstName} ${this.lastName}`
   }
}
const firstPerson= new Person ("Thor", "Odinson")
console.log(firstPerson.sayName())

And below an example of a method creation from outside the scope of a class using a prototype:

class Person {
   constructor(fName, lName) {
      this.firstName = fName;
      this.lastName = lName;
   }
}
Person.prototype.sayName = function() {
   return `My Name is ${this.firstName} ${this.lastName}`
}
const secondPerson= new Person ("Tony", "Stark")
console.log(secondPerson.sayName())

A very important thing to note is that using prototype to add a method to a class doesn't change the structure of the class. So logging the object won't render the method. But the method is available to all subclasses and instances of that class.

You can use Object.setPrototypeOf.

Example:

// A class…
class Someone {
  constructor(qui){
    this.qui = qui
  } 
}

// A mixins with new methods
class MyMixins {
  says(quoi){
    console.log(this.qui + " says "+ quoi)
  }
  eats(quoi){
    console.log(this.qui + " eats "+quoi)
  }
}

// An instance…
const marion = new Someone("Marion")

// This fails…
//marion.says("hello!")
//marion.eats("potatoes")

//-----> Here's the trick <------
Object.setPrototypeOf(Someone.prototype, MyMixins.prototype);

// This pass…
marion.says("hello!")   //=> "Marion says hello!"
marion.eats("potatoes") //=> "Marion eats potatoes"
Related