【问题标题】:.apply without changing scope.apply 不改变范围
【发布时间】:2012-11-23 16:09:50
【问题描述】:

我想将 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]按预期返回值,但应用调用[2]总是在[0]行产生以下错误:

TypeError: Cannot set property 'NaN' of undefined

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

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

【问题讨论】:

  • foo.apply(null,…) 产生同样的错误
  • 如果您希望保留默认范围,我很好奇您为什么要首先使用 apply 方法...
  • @subhaze:我为这个例子简化了它。我需要参数的数量是可变的,因为大多数 Nimbus 函数期望的不仅仅是回调作为参数。
  • 啊,好的。您是否偶然尝试过client[req.params.command].apply(client, [console.log]);

标签: javascript node.js scope


【解决方案1】:

像这样将apply 函数指向同一个函数应该保留原来的作用域。

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-29
  • 2013-10-02
  • 1970-01-01
  • 2016-07-15
  • 2017-08-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多