I want to use the JavaScript .apply method to functions of a thrift compiled for Node.js. The thrift .js file has code like this:
...
var NimbusClient = exports.Client = function(output, pClass) {
this.output = output;
this.pClass = pClass;
this.seqid = 0;
this._reqs = {};
};
NimbusClient.prototype = {};
NimbusClient.prototype.getClusterInfo = function(callback) {
this.seqid += 1; // line where error is thrown [0]
this._reqs[this.seqid] = callback;
this.send_getClusterInfo();
};
...
My server file looks the following way:
var thrift = require('thrift')
, nimbus = require('./Nimbus')
, connection = thrift.createConnection('127.0.0.1', 6627)
, client = thrift.createClient(nimbus, connection)
, ... // server initiation etc
app.get('/nimbus/:command', function(req, res, next) {
client[req.params.command](console.log); // direct call [1]
client[req.params.command].apply(this, [console.log]); // apply call [2]
});
...
The direct call [1] returns the values as expected, but the apply call [2] always produces the following error in line [0]:
TypeError: Cannot set property 'NaN' of undefined
I tried several other scope parameters in [2]: null
, nimbus
, nimbus.Client
, nimbus.Client.prototype
, nimbus.Client.prototype[req.params.command]
and client[req.params.command]
, all without success.
How can I call the apply method without changing the actual scope of the function called, so that it behaves exactly the same as it would if called in the direct way?
Pointing the apply
function back to the same function like this should retain the original scope.
client[req.params.command].apply(client, [console.log]);