如何在JavaScript中动态创建静态方法? [英] How to dynamically create static method in JavaScript?
本文介绍了如何在JavaScript中动态创建静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有这个:
class Math {
static add(a, b) {
return a + b
}
}
我想把它变成:
class Math {
static add(a, b) {
return a + b
}
static subtract(a, b) {
return a - b
}
}
有没有办法动态地做到这一点?例如.
Is there a way to do it dynamically? eg.
class Math {
static add(a, b) {
return a+b
}
}
Math.extend({
subtract: function(a, b) {
return a-b
}
})
Math.subtract(1,1) // 0
推荐答案
静态方法只不过是构造函数上的方法.因此,您需要做的就是将方法分配给Math
:
Static methods are nothing but methods on the constructor. So all you need to do is assign the methods to Math
:
Object.assign(Math, {
subtract(a, b) {
return a - b
}
});
这篇关于如何在JavaScript中动态创建静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文