我需要使用新语法向 Javascript 类添加一个方法。我试过这种方式:
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.
它只是打印:
class X{
constructor() {
this.a = 'b'
}
x(){}
}
但我预料到了
class X{
constructor() {
this.a = 'b'
}
x(){}
y(){
console.log('y');
}
}
如何向 Javascript 类添加新方法?
最佳答案
这工作正常,如果您在 google chrome 控制台中检查它,请通过展开 proto 节点进行检查。
或者尝试检查
console.log(X.y)
或 console.log(X.prototype.y)
或 console.log(x.y)
这必须打印那个函数
关于javascript - 如何向 Javascript ES6 中的类添加方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35813851/