JavaScript"这个"嵌套函数中的指针

时间:2014-06-18 16:46:52

标签: javascript function pointers this

以下是一些不起作用的JavaScript代码:

function clientEventsManager(io) {
    this.connectedClients = 0;

    this.createEventReceivers = function(io) {
        io.sockets.on('connection', function(socket) {
                this.connectedClients++;
                //does not increase "connectedClients" of "clientEventsManager" function
        }
    }

    createEventReceivers(io); //it is the only call to createEventReceivers()
}



var Manager = new clientEventsManager(io); //it is the only instanciation of clientEventsManager

我的问题是:是否有办法在clientEventsManager.createEventReceivers()中更改clientEventsManager.connectedClients?

编辑:这篇文章是this one的副本,谢谢你回答

1 个答案:

答案 0 :(得分:-2)

快速而肮脏的解决方案

function base(param) {
    this.attr1 = "azertyuiop";
    this.attr2 = 123;
    this.attr3 = param;
    var self=this;
    this.fct1 = function() {
        console.log("azerty keyboard first row: "+self.attr1);
        //Doesn't work
    }
}