[removed] prototypes with callbacks and 'this'

后端 未结 3 1069
庸人自扰
庸人自扰 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:28

    self = this

    Your creating a global variable, that's why your code is broken.

    Also trying to reference self inside the prototype does not work, use this

    function Person(name){
        this.name = name
    }
    
    Person.prototype = {
        openConnection : function(host, port){
            this.pointCount = 0
            this.ws = new WebSocket("ws://" + host + ":" + port)
            this.ws.onopen = this.onOpenConnection.bind(this)
        },
        constructor: Person,    
        onOpenConnection : function()   {
            console.log(this) // prints the person
            this.ws.send(this.name) // works only if one person exists
        }
    }
    

提交回复
热议问题