2012-12-05 22 views
6

JavaScript.applyメソッドをNode.js用にコンパイルされた関数に使用します。倹約.jsファイルには、このようなコードを持っています.applyスコープを変更しないでください。

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:

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

私のサーバーのファイルは次のように見えますnullnimbusnimbus.Client、:I [2]におけるいくつかの他のスコープのパラメータを試し

TypeError: Cannot set property 'NaN' of undefined 

:]常にライン[0]に次のエラーを生成します,nimbus.Client.prototype[req.params.command]およびclient[req.params.command]、これらは全て成功していない。

呼び出される関数の実際のスコープを変更せずにapplyメソッドを呼び出すと、直接呼び出した場合とまったく同じように動作します。

+0

トライfoo.apply(NULL、...) –

+0

foo.apply(ヌルは、...)同じエラー – Thomas

+0

を生成し、私は一種の好奇心、あなたが最初に 'apply'メソッドを使用したい理由としててりますデフォルトのスコープを保持したい場合は置き換えてください。 – subhaze

答えて

11

applyの機能をこのような同じ機能に戻すと、元の範囲が保持されます。

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

これは、[coffeescriptが配列引数を関数引数としてコンパイルする方法](http://tinyurl.com/baz8ryz) 'obj.fn(arr ...)' –

関連する問題