2012-12-05 80 views
6

我想使用JavaScript .apply方法来编译Node.js节点的函数。节俭的.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]的预期收益值,但该申请调用[2 ]总是产生在管线[0]以下错误:

TypeError: Cannot set property 'NaN' of undefined 

我试图在[2]其他几个范围参数:nullnimbusnimbus.Clientnimbus.Client.prototype,nimbus.Client.prototype[req.params.command]client[req.params.command],都没有成功。

如何在不改变被调用函数的实际范围的情况下调用apply方法,使其与直接调用时的行为完全相同?

+0

尝试foo.apply(NULL,...) –

+0

foo.apply(NULL,...)产生同样的错误 – Thomas

+0

我好心的好奇,为什么你要使用'apply'方法在第一如果你想保留默认范围的地方... – subhaze

回答

11

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

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

这正是[coffeescript编译数组splats作为函数参数](http://tinyurl.com/baz8ryz)'obj.fn(arr ...)' –