Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript function scope issues

I'm working on a little Websockets demo and I've got a scope issue I can't sort.

network = function () {

    this.host = "ws://localhost:8002/server.js";
    this.id = null;

    this.init = function (s) {
        var scene = s;

        try {
            socket = new WebSocket(this.host);

            socket.onopen = function (msg) {
            };

            socket.onmessage = function (msg) {
                switch(msg.data[0]) {
                case 'i':
                    var tmp = msg.data.split('_');

                    // cant access this function.
                    this.setId(tmp[1]);

                    break;
                }
            };

            socket.onclose = function (msg) {
            };
        }
        catch (ex) {}
    };

    this.setId = function(id) {
        this.id = id;
    };
};

How can I access this.setId() from the socket.onmessage event?

like image 437
harrynorthover Avatar asked Jun 27 '26 16:06

harrynorthover


1 Answers

network = function () {
    var self = this;

    this.host = "ws://localhost:8002/server.js";
    this.id = null;

    this.init = function (s) {
        var scene = s;

        try {
            socket = new WebSocket(self.host);

            socket.onopen = function (msg) {
            };

            socket.onmessage = function (msg) {
                switch(msg.data[0]) {
                case 'i':
                    var tmp = msg.data.split('_');

                    // cant access this function.
                    self.setId(tmp[1]);

                    break;
                }
            };

            socket.onclose = function (msg) {
            };
        }
        catch (ex) {}
    };

    this.setId = function(id) {
        self.id = id;
    };
};

preserving a reference like this should do it. anytime you reference this in a function, replace this with self.

like image 119
meder omuraliev Avatar answered Jun 30 '26 07:06

meder omuraliev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!