gpt4 book ai didi

ecmascript-6 - ES6 : If class has method?

转载 作者:行者123 更新时间:2023-12-04 04:21:11 25 4
gpt4 key购买 nike

我有一个带有调用其他方法的方法的类:

class MyClass {
build(methods) {
methods.forEach((method) => {
if (this.method) {
this.method();
}
});
}

stuff() {}
moreStuff() {}
}

const a = MyClass();
a.build(['stuff', 'moreStuff']);

我还没有找到任何关于类的特殊方法的引用。我的第一个想法是使用 hasOwnProperty (但是 eslint 唠叨我不应该在类里面使用它)。由于类具有内置函数,因此上述方法无法可靠地工作。

我也在看 Reflect可能是我的救命稻草,但我真的可以使用一些指导来了解这种情况的最佳实践是什么?

最佳答案

我想你正在寻找

build (methodnames) {
for (const methodname of methodnames) {
if (typeof this[methodname] == "function") {
this[methodname]();
}
}
}

类没有什么特别之处——事实上你应该忽略它们。如果要调用某个方法,唯一重要的是有一个函数作为属性值。方法是否是创建实例的类的原型(prototype)对象的自有属性并不重要。

关于ecmascript-6 - ES6 : If class has method?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39649658/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com