Search code examples
javascriptclassmethodsprototypeecmascript-5

How to add an method to a class in Javascript ES6


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?


Solution

  • 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