Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 933
Natanael Avatar asked Mar 05 '16 12:03

Natanael


1 Answers

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

like image 82
Ammar Hasan Avatar answered Sep 18 '22 18:09

Ammar Hasan