javascript - 如何在 Javascript 中将一个函数的响应提供给另一个函数?

标签 javascript node.js class

我有一堂这样的课:

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)
  }
}

现在我希望能够以以下不同的方式使用上述类,如下所示 res1res2

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/

相关文章:

javascript - 在 Internet Explorer 11 中通过 fetch-api 发布 FormData 对象时的空值

javascript - 查找日期在范围内,时刻失败

javascript - jQuery Draggable - 获取可拖动的 id

javascript - 可以找出是什么干扰了之前运行良好的 jquery 代码吗?

javascript - Node - 无效的数组长度

javascript - "Can' t 发送后设置 header ”和清空发布请求正文

javascript - 在聚合调用中限制字段属性的更好方法

python - 返回类中的元素,Python。美丽汤

Python Class() 没有参数错误。我正在使用 self

c++ - 当派生类添加了数据成员时,派生类的构造函数应该如何在 C++ 中使用