WebSocket的'onopen()'函数内的对象方法调用给出'函数未定义'

时间:2017-01-08 06:57:50

标签: javascript websocket

我正在尝试编写一个基于JavaScript的ChatClient,并希望在'onopen'或'onmessage'函数中调用一些其他对象方法,如'this.some()'。怎么了?

var ChatClient = function() {

    this.me = null; // This user

    this.others = []; // Other users

    this.socket = null;

    this.handshake = function() {

        this.socket = new WebSocket("ws://" + "localhost" + ":8000");

        // Error occurred
        this.socket.onerror = function(error) {

            console.log('Socket error: ' + error);
        };

        // Opened
        this.socket.onopen = function() {

            console.log('Socket opened');

            this.some(); // <== Error: this.some is undefined
        };

        // Message received
        this.socket.onmessage = function(message) {

            console.log('Socket message: ' + message.data);
        };

        // Closed
        this.socket.onclose = function(message) {

            console.log('Socket message: ' + message.data);
        };
    };

    this.someOther = function() {

        alert('name');
    }

    this.some = function() {

        this.someOther();
    }
}

1 个答案:

答案 0 :(得分:2)

您正在尝试访问异步调用中的this,这在套接字打开时将不会出现。这导致this.some()未定义。

下面的代码应该有效:

var ChatClient = function() {

    var _self = this; // Save outer context
    this.me = null; // This user
    this.others = []; // Other users

    this.socket = null;

    this.handshake = function() {

        this.socket = new WebSocket("ws://" + "localhost" + ":8000");

        // Error occurred
        this.socket.onerror = function(error) {

            console.log('Socket error: ' + error);
        };

        // Opened
        this.socket.onopen = function() {

            console.log('Socket opened');

            _self.some(); //It should work
        };

        // Message received
        this.socket.onmessage = function(message) {

            console.log('Socket message: ' + message.data);
        };

        // Closed
        this.socket.onclose = function(message) {

            console.log('Socket message: ' + message.data);
        };
    };

    this.someOther = function() {

        alert('name');
    }

    var some = function() {

        this.someOther();
    }
}

您调用this.some()的方式中的问题是this的引用已经从ChatClient的上下文更改为WebSocket.open方法。如果你想使用外部上下文,你需要将上下文存储在一些变量中.eg:_this或self;

var _self = this;

然后使用_self.some调用外部函数或变量。

PS:编辑答案请检查:)