Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.apply without changing scope

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?

like image 371
Thomas Avatar asked Dec 05 '12 18:12

Thomas


People also ask

What does apply() do?

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.

What is the use function prototype apply method?

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 is a scoping function?

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.

When to use js apply?

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() .


1 Answers

Pointing the apply function back to the same function like this should retain the original scope.

client[req.params.command].apply(client, [console.log]);
like image 60
subhaze Avatar answered Oct 15 '22 15:10

subhaze