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?
Summary. The apply() method invokes a function with a given this value and arguments provided as an array. The apply() method is similar to the call() method excepts that it accepts the arguments of the function as an array instead of individual arguments.
prototype. apply() The apply() method calls the specified function with a given this value, and arguments provided as an array (or an array-like object).
What are scope functions? In Kotlin, scope functions are used to execute a block of code within the scope of an object. Generally, you can use scope functions to wrap a variable or a set of logic and return an object literal as your result. Therefore, we can access these objects without their names.
Use Apply() to Append an Array to Another Array This means you have an array inside an array. Here you can use concat() but it creates a new array. If you want to append an array as a whole into an existing array, use apply() .
Pointing the apply
function back to the same function like this should retain the original scope.
client[req.params.command].apply(client, [console.log]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With