How to add an method to a class in Javascript ES6

Natanael picture Natanael · Mar 5, 2016 · Viewed 21.5k times · Source

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?

Answer

Ammar Hasan picture Ammar Hasan · Mar 5, 2016

this works fine, if you are checking this in google chrome console, then please check by expanding proto node. or alternatively try checking console.log(X.y) or console.log(X.prototype.y) or console.log(x.y) this must print that function