11

我创建了一个基于原型的类Person,它打开一个 WebSocket 连接并将回调函数定义为原型方法。

因为在回调内部this将引用 WebSocket 对象,所以我使用了另一个变量来保留Person. this但是,当我处理多个实例时,变量会被覆盖。

这是一个显示问题的小片段:

function Person(name){
    self = this
    self.name = name
}

Person.prototype = {
    getName : function(){
        return self.name
    },

    openConnection : function(host, port){
        self.pointCount = 0
        self.ws = new WebSocket("ws://" + host + ":" + port)
        self.ws.onopen = self.onOpenConnection
    },

    onOpenConnection : function()   {
        console.log(this) // prints the websocket
        console.log(self) // prints the person
        self.ws.send(self.name) // works only if one person exists
    }
}

var p1 = new Person("Jonh")
var p2 = new Person("Adam")

console.log(p1.getName()) // Prints Adam
console.log(p2.getName()) // Prints Adam

p1.openConnection("localhost", 7000) // opens connection for p1
p2.openConnection("localhost", 7000) // opens another connection for p1    

如果Person创建了多个,则在尝试通过套接字发送消息时出现以下错误:

未捕获的错误:INVALID_STATE_ERR:DOM 异常 11

所以它似乎self是全局定义的,我试图在回调中获取Person' 的句柄失败了。this关于如何实现这一目标的任何建议?

4

3 回答 3

13

当你这样做时:

self = this

您正在隐式创建一个全局变量,该变量(因为它是全局的)对于所有实例都具有相同的值。局部变量,必须有varletconst在它们前面,如以下之一:

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

但是,这不是您的解决方案。您需要改为使用this。而且,如果您要为 websocket 提供回调并且您希望与此关联的人,我建议您只需在 websocket 上放置对 Person 对象的引用,然后您就可以从那里检索它。而且,每条语句的结尾都缺少分号是怎么回事?无论如何,这里有一些固定的代码:

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
    }
}
于 2012-04-04T15:48:55.620 回答
5

在 Javascript 中声明变量时,如果您不将 avar放在前面,它将被视为全局变量,这会在您的情况下导致一些问题。

当构造函数按预期运行时,您可能希望执行以下操作,因此name保存到您正在创建的 Person 实例中:

// Constructor
function Person(name){
    // You don't need to reference "self" here. It's already implied.
    this.name = name;
}

此外,在 WebSocket.onopen 中,“this”从 Person 的实例变为 WebSocket 的实例。您需要保留“Person”以便在 WebSocket.onopen 中引用它。

// Prototype
Person.prototype = {
    getName : function(){
        // 'this' in this case refers to an instance of Person. 
        // So, when creating John, this.name will be John. 
        return this.name;
    },

    openConnection : function(host, port) {
        // Similar to getName(...), this refers to an instance of Person.
        // In your example, this.pointCount is NOT shared between John and Adam
        this.pointCount = 0;
        this.ws = new WebSocket("ws://" + host + (port ? ':' + port : ''));

        // In WebSocket.onopen below, you're working with a new scope, so you 
        // won't have access to 'this' as the Person anymore. You need to save 
        // 'this' somewhere, so you can reference it in the new scope.
        // *****
        var self = this;   

        this.ws.onopen = function() {
            // In this function, a new scope has been created. 'this' no 
            // longer refers to John/Adam (The instance of Person), but to 
            // WebSocket instead.

            console.log(this); // 'this' references the WebSocket instance
            console.log(self); // 'self' references the 'self' in the outer 
                               // scope. See *****

            // Since this = WebSocket in this scope, all we need to do
            // is this.send(...). If you'd like to obtain the refer
            // to the instance of the Person you worked with, you can
            // use the 'self' variable
            this.send(self.name); 
        };
    }
};

希望这可以帮助!这是一个与之配套的 JSFiddle:http: //jsfiddle.net/WFdbe/

于 2012-04-04T16:12:40.150 回答
1

self = this

您创建了一个全局变量,这就是您的代码被破坏的原因。

尝试self在原型内部引用也不起作用,请使用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
    }
}
于 2012-04-04T15:45:00.317 回答