我有一堂这样的课:
class MyModule {
constructor() {
this.val = 0;
}
foo(a,b) {
this.val = a+b;
return this.val
}
bar() {
return this.val + 10
}
silly() {
return __isGreaterThan(50)
}
}
现在我希望能够以以下不同的方式使用上述类,如下所示 res1
和 res2
。
const xyz = require('myModule');
const res1 = xyc.foo(5,10).bar().silly();
const res2 = xyz.foo(5,10);
console.log(res1) // Outputs --> false
console.log(res2) // Outputs --> 15
最佳答案
这是一个示例,只需对代码进行最小的更改即可输出您想要的内容
注意:在您的代码中,您永远不会创建 MyClass 的实例,我认为您需要了解类的工作原理
class MyModule {
constructor() {
this.val = 0;
}
foo(a,b) {
this.val = a+b;
return this;
}
bar() {
this.val += 10;
return this;
}
silly() {
return this.val > 50;
}
}
// in a separate file, you'd do something like
//
// const MyModule = require('myModule');
//
// obviously, won't work in this snippet, but that's the only difference
// with what your real world code would need
const xyc = new MyModule();
const xyz = new MyModule();
const res1 = xyc.foo(5,10).bar().silly();
const res2 = xyz.foo(5,10).val; // note: you need to get the `val` property
console.log(res1) // Outputs --> false
console.log(res2) // Outputs --> 15
关于javascript - 如何在 Javascript 中将一个函数的响应提供给另一个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51316709/