如何在Javascript中将一个函数的响应反馈给另一个函数?

时间:2018-07-13 02:00:38

标签: 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

1 个答案:

答案 0 :(得分:1)

这是一个示例,只需很少的代码更改即可输出所需的内容

注意:在您的代码中,您永远不会创建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