。应用而不改变范围

时间:2012-12-05 18:25:58

标签: javascript node.js scope

我想将JavaScript .apply方法用于为Node.js编译的thrift的函数。 thrift .js文件的代码如下:

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

我的服务器文件看起来如下:

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]
});

...

直接调用[1]按预期返回值,但apply call [2]总是在行[0]中产生以下错误:

TypeError: Cannot set property 'NaN' of undefined

我在[2]中尝试了其他几个范围参数:nullnimbusnimbus.Clientnimbus.Client.prototypenimbus.Client.prototype[req.params.command]client[req.params.command],一切都没有成功。

如何调用apply方法而不更改所调用函数的实际范围,以便它的行为与直接调用时的行为完全相同?

1 个答案:

答案 0 :(得分:12)

apply函数指向这样的相同函数应该保留原始范围。

client[req.params.command].apply(client, [console.log]);