gpt4 book ai didi

Javascript 函数作用域问题

转载 作者:行者123 更新时间:2023-11-29 22:37:57 25 4
gpt4 key购买 nike

我正在做一个 Websockets 的小演示,但遇到了一个我无法解决的范围问题。

network = function () {

this.host = "ws://localhost:8002/server.js";
this.id = null;

this.init = function (s) {
var scene = s;

try {
socket = new WebSocket(this.host);

socket.onopen = function (msg) {
};

socket.onmessage = function (msg) {
switch(msg.data[0]) {
case 'i':
var tmp = msg.data.split('_');

// cant access this function.
this.setId(tmp[1]);

break;
}
};

socket.onclose = function (msg) {
};
}
catch (ex) {}
};

this.setId = function(id) {
this.id = id;
};
};

如何从 socket.onmessage 事件访问 this.setId()?

最佳答案

network = function () {
var self = this;

this.host = "ws://localhost:8002/server.js";
this.id = null;

this.init = function (s) {
var scene = s;

try {
socket = new WebSocket(self.host);

socket.onopen = function (msg) {
};

socket.onmessage = function (msg) {
switch(msg.data[0]) {
case 'i':
var tmp = msg.data.split('_');

// cant access this function.
self.setId(tmp[1]);

break;
}
};

socket.onclose = function (msg) {
};
}
catch (ex) {}
};

this.setId = function(id) {
self.id = id;
};
};

保留这样的引用应该可以做到。每当您在函数中引用 this 时,请将 this 替换为 self

关于Javascript 函数作用域问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4292989/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com