JS: How to do function.function(param).function?
javascript, node.js
Solution
It is called `Method Chaining` or sometimes `Fluent interface`. The main idea behind the 'chaining' is to return an `object` (often times `self`) as a result, enabling direct invocation on the returned value.
I copied a sample code from here (attribute goes to the original author) that returns `self` as a return value.
var obj = {
function1: function () {
alert("function1");
return obj;
},
function2: function () {
alert("function2");
return obj;
},
function3: function () {
alert("function3");
return obj;
}
}
obj.function1().function2().function3();
For your `FOO` implementation, try returning `this` at the end of `bars` function.
FOO.prototype.bars = function(index,value){
// your previous code here;
this.value = value;
return this;
}
Problem
Thanks for reading. So I am working on a my first node.js app. I'm relatively familiar with javascript but not well enough. I have declared a class `FOO` with a method called `bars(index, value}` that accepts 2 params. In order do use this, after creating an instance, I have the following `fooInstance.bars(3, 2)` I would like to call this method a bit differently. How can I change my `FOO` definition so that I can use it like this `fooInstance.bars(3).value`? My current code is below ``` 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; } } ``` thanks in advance!