JavaScript:带有回调和'this'的原型



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

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

以下是显示问题的小片段:

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是全局定义的,我试图在回调中获得Personthis的句柄失败了。关于如何实现这一目标,有什么建议吗?

当你这样做时:

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
    }
}

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

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

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

此外,在WebSocket.open中,"this"从Person的实例更改为WebSocket的实例。您需要保留"Person"以便在WebSocket.onpen.中引用它

// 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/

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
    }
}

相关内容

  • 没有找到相关文章

最新更新