js - 'this'在调用方法'间接'时是未定义的 [英] js - 'this' is undefined when calling method 'indirectly'

查看:93
本文介绍了js - 'this'在调用方法'间接'时是未定义的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是从函数表调用函数来概括命令处理(即间接)。不幸的是,这个在被调用时是 undefined

My goal is to call a function from a table of functions to generalize command handling (i.e indirectly). Unfortunately, this isundefined when called as such.

function Server() {
    this.sessions = {};

    server = this;
    this.handlers = {
        "dummy" : server.dummyCommandHandler,
    };
}

Server.prototype.dummyCommandHandler = function() {
    print (this.sessions);
}

Server.prototype.run = function ( command ) {
    print (this.sessions); // [Object object]
    this.handlers[command.name](); // prints 'undefined'
    this.dummyCommandHandler(); // prints '[Object object]'
}

s = new Server();
s.run({ "name": "dummy" });

这是我第一次使用javascript,我认为我确定了范围,但显然它更多似乎很复杂。使用服务器变量对别名服务器的没有帮助(我想也许这个处理程序对象中更改。当间接调用函数时,这个的范围是什么?

This is my first time using javascript, and I thought I had the scoping down but apparently it is more complicated than it seems. Aliasing Server's this with the server variable didn't help (I thought perhaps this changes hands within the handlers object). What is the scope of this when the function is called indirectly?

推荐答案

的默认行为是它指的是调用时的函数范围(见下文)。你可以使用 bind 强制这个的值( MDN )或使用箭头函数语法,它将您对<$ c的引用的词法范围$ c> this 到你定义函数的任何地方。这是我要做的改变:

The default behavior for this is that it refers to the function scope at the time it's invoked (see below). You can force the value of this by either using bind (MDN) or using arrow function syntax, which lexically-scopes your references to this to wherever you defined the function. This is the change I would make:

dummy:server.dummyCommandHandler.bind(this),

这篇关于js - 'this'在调用方法'间接'时是未定义的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆