Javascript函数范围问题

Javascript函数范围问题,javascript,scope,Javascript,Scope,我正在做一个Websockets的小演示,我有一个无法排序的范围问题 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);

我正在做一个Websockets的小演示,我有一个无法排序的范围问题

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;
    };
};
如何从socket.onmessage事件访问this.setId

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;
    };
};
保存这样的引用就可以了。在函数中引用此项时,请将其替换为self