JS:怎么做function.function(param).function?

Erv*_*n E 3 javascript node.js

谢谢阅读.

所以我正在开发我的第一个node.js应用程序.我对javascript比较熟悉但不够好.

我已经声明了一个类FOO,该方法调用了bars(index, value}一个接受2个参数的方法.为了使用它,在创建实例后,我有以下内容fooInstance.bars(3, 2)

我想把这种方法称为有点不同.如何更改我的FOO定义以便我可以像这样使用它fooInstance.bars(3).value

我目前的代码如下

var util = require('util'),
  events = require('events');

var FOO = function(opts) {
  this.ipAddress = opts.ipAddress;
  this.port = opts.port;
};

FOO.prototype = new events.EventEmitter;
module.exports = FOO;

FOO.prototype.bars = function (index, value) {
  switch(index) {
    case 1:  
      console.log("Apple " + " at " + value)
      break;
    case 2:
      console.log("Banana, " + " at " + value)
      break;
    case 3: 
      console.log("Cherry, " + " at " + value)
      break;
    case 4:
      console.log("Date, " + " at " + value)
      break;
    default:
      break;
  }
}
Run Code Online (Sandbox Code Playgroud)

提前致谢!

Kit*_*ita 5

它被称为Method Chaining或有时Fluent interface."链接"背后的主要思想是返回object(通常是时间self)结果,允许直接调用返回值.

我从这里复制了一个示例代码(属性转到原作者),它返回self一个返回值.

var obj = {
        function1: function () {
            alert("function1");
            return obj;
        },
        function2: function () {
            alert("function2");
            return obj;
        },
        function3: function () {
            alert("function3");
            return obj;
        }
    }


obj.function1().function2().function3();
Run Code Online (Sandbox Code Playgroud)

对于您的FOO实现,请尝试thisbars函数结束时返回.

FOO.prototype.bars = function(index,value){
  // your previous code here;
  this.value = value;
  return this;
}      
Run Code Online (Sandbox Code Playgroud)