Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
191
rated 0 times [  196] [ 5]  / answers: 1 / hits: 44161  / 8 Years ago, sat, march 5, 2016, 12:00:00

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?


More From » class

 Answers
33

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


[#63037] Thursday, March 3, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
theron

Total Points: 168
Total Questions: 93
Total Answers: 94

Location: South Georgia
Member since Fri, Nov 13, 2020
4 Years ago
;