javascript - .apply 不改变范围

标签 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] 按预期返回值,但应用调用 [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 方法,使其行为与直接调用时完全相同?

最佳答案

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

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

关于javascript - .apply 不改变范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13729918/

相关文章:

javascript - AngularJS:将字符串拆分为数组,获取第一个元素

javascript - 如何在 Apple JS 中使用 "Sign In with Apple"

javascript - 导致 infdig 的过滤器/函数

node.js - 出现错误 : Can't set headers after they are sent

node.js - Babel 和 Bluebird promise

Node.js v4 迁移(适用于 sails.js 或 node.js)

go - 在条件语句中声明但未使用的变量

javascript - 我可以从网络浏览器获取操作系统吗?

javascript - 为什么我的输入元素在回发后不保留焦点/模糊事件?

javascript - 从 JavaScript 对象访问父函数