[removed] prototypes with callbacks and 'this'

后端 未结 3 1071
庸人自扰
庸人自扰 2020-12-31 10:47

I\'ve create a prototype based class Person that opens a WebSocket connection and defines callback functions as prototype methods.

Because inside the ca

3条回答
  •  一生所求
    2020-12-31 11:17

    When you do:

    self = this
    

    You are implicitly creating a global variable which (since it's global) will have the same value for all instances. Local variables, must have var, let or const in front of them like one of these:

    var self = this;
    const self = this;
    let self = this;
    

    But, that isn't your solution here. You need to be using this instead. And, if you're going to supply a callback for the websocket and you want the person associated with that, I would suggest you just put a reference to the Person object on the websocket so you can then retrieve it from there. And, what's with all the missing semicolons to end each statement? Anyway, here is some fixed up code:

    function Person(name){
        this.name = name;
    }
    
    Person.prototype = {
        getName : function(){
            return this.name;
        },
    
        openConnection : function(host, port){
            this.pointCount = 0;
            this.ws = new WebSocket("ws://" + host + ":" + port);
            // save person reference on the web socket
            // so we have access to the person from web socket callbacks
            this.ws.person = this;   
            this.ws.onopen = this.onOpenConnection;
        },
    
        onOpenConnection : function()   {
            // "this" will be the websocket
            // "this.person" is the person object
            console.log(this); // prints the websocket
            console.log(this.person); // prints the person
            this.send(this.person.name); // works only if one person exists
        }
    }
    

提交回复
热议问题