javascript - 如何向 Javascript ES6 中的类添加方法

标签 javascript class methods prototype ecmascript-5

我需要使用新语法向 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/

相关文章:

python - 在 Python 3 中创建一个 Account 类

php - PHP中的动态静态方法调用?

c# - 如何在 C# 中从函数返回结构?

javascript - 如何在子类中定义 getter 和 setter 属性

javascript - 菜单栏功能无法使用 javascript

java - 如果我没有在该特定类中声明它,如何在该类上调用 getItem 方法

java - 如何在公共(public)方法中使用私有(private)方法来检查有效性?

php - 我怎样才能说服我的客户试图隐藏浏览器工具栏是个坏主意?

javascript - Ajax 注释插入 LI 或替换 UL?

java - 创建一种方法以从索引 x 到索引 y 中删除 ArrayList 元素