如何避免重复的JS代码,每个人都使用它?
我有几个不同的类,具有相同的重复代码。除了每个的不同身份外,这些重复的代码表面上都是相同的。
这是一个简化的示例:
class classA {
...
doSomething() {
if (!this.id || !this.data || !this.isAllowed()) {
return null;
}
return someImportedFunc(this.data, this.metadata, this.doSomethingElse());
}
}
class classB {
...
doSomething() {
if (!this.id || !this.data || !this.isAllowed()) {
return null;
}
return someImportedFunc(this.data, this.metadata, this.doSomethingElse());
}
}
// Many other classes like this
我已经考虑过将dosomething
方法移至另一个类,然后在所有这些类中导入它。但这将导致一种非常混乱的方法,该方法需要许多参数来解释所有不同的this
的s。看起来像:
class exportedClass {
function doSomething(id, data, metadata, isAllowed, doSomethingElse) {
if (!id || !data || !isAllowed()) {
return null;
}
return someImportedFunc(data, metadata, doSomethingElse());
}
}
class classA {
...
methodThatUsesDoSomething() {
const result = exportedClass.doSomething(
this.id, this.data, this.metadata, this.isAllowed, this.doSomethingElse);
...
}
}
除了15个args而不是5个,因为这是一个简化的示例。
在这种情况下,如何避免重复代码?
I have several different classes with the same duplicate code. Aside from the different identity of each's this
, these duplicate code are all ostensibly identical.
Here's a simplified example:
class classA {
...
doSomething() {
if (!this.id || !this.data || !this.isAllowed()) {
return null;
}
return someImportedFunc(this.data, this.metadata, this.doSomethingElse());
}
}
class classB {
...
doSomething() {
if (!this.id || !this.data || !this.isAllowed()) {
return null;
}
return someImportedFunc(this.data, this.metadata, this.doSomethingElse());
}
}
// Many other classes like this
I've thought of moving the doSomething
method to another class, then importing it in all these classes. But that would result in a very messy method that takes many, many arguments to account for all the different this
's. It'd look like:
class exportedClass {
function doSomething(id, data, metadata, isAllowed, doSomethingElse) {
if (!id || !data || !isAllowed()) {
return null;
}
return someImportedFunc(data, metadata, doSomethingElse());
}
}
class classA {
...
methodThatUsesDoSomething() {
const result = exportedClass.doSomething(
this.id, this.data, this.metadata, this.isAllowed, this.doSomethingElse);
...
}
}
Except with like 15 args instead of 5 since this is a simplified example.
How can I avoid duplicate code in this kind of situation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
假设您想要一个非传播解决方案,我的建议是将“此”作为参数传递,因为可以将原型操纵为参数。这将使您能够将参数保持在最低限度,同时又不丢失数据。
Assuming you want a non-inheritance solution, my suggestion would be to pass "this" as an argument, as prototypes can be manipulated as parameters. That would allow you to keep the parameters at a minimum while not losing data.