TypeScript 和 SocketIO,事件范围解析
TypeScript and SocketIO, scope resolution on events
我正在使用 socketio 的 Definitely Typed typescript 定义文件,但在尝试绑定事件时遇到范围问题。
module testScope {
import Socket = SocketIOClient.Socket;
export class testClass {
socket: Socket;
constructor(){
this.socket = io.connect();
this.socket.on('test', this.testCallback);
}
testCallback(){
console.log(this);
}
}
}
console.log 调用输出一个 Socket 对象而不是 testClass 对象。有什么办法可以解决这个问题吗?如果可能,不添加另一层事件系统。
这样做也是不行的,"this"没有方法testCallback:
module testScope {
import Socket = SocketIOClient.Socket;
export class testClass {
socket: Socket;
constructor(){
this.socket = io.connect();
this.socket.on('test', function(){ this.testCallback(); });
}
testCallback(){
console.log(this);
}
}
}
即使您正在使用 classes,class 方法中 this 的作用域规则仍然与 [=26= 中的相同] 函数(方法在转译后最终成为函数)。
改为使用箭头函数来保持相同的词法作用域。
module testScope {
import Socket = SocketIOClient.Socket;
export class testClass {
socket: Socket;
constructor(){
this.socket = io.connect();
this.socket.on('test', () => this.testCallback()); // this is now testClass
}
testCallback(){
console.log(this);
}
}
}
您可以找到更多关于 this 工作原理的信息 here。
您可以找到有关箭头函数的更多信息 here。
我正在使用 socketio 的 Definitely Typed typescript 定义文件,但在尝试绑定事件时遇到范围问题。
module testScope {
import Socket = SocketIOClient.Socket;
export class testClass {
socket: Socket;
constructor(){
this.socket = io.connect();
this.socket.on('test', this.testCallback);
}
testCallback(){
console.log(this);
}
}
}
console.log 调用输出一个 Socket 对象而不是 testClass 对象。有什么办法可以解决这个问题吗?如果可能,不添加另一层事件系统。
这样做也是不行的,"this"没有方法testCallback:
module testScope {
import Socket = SocketIOClient.Socket;
export class testClass {
socket: Socket;
constructor(){
this.socket = io.connect();
this.socket.on('test', function(){ this.testCallback(); });
}
testCallback(){
console.log(this);
}
}
}
即使您正在使用 classes,class 方法中 this 的作用域规则仍然与 [=26= 中的相同] 函数(方法在转译后最终成为函数)。
改为使用箭头函数来保持相同的词法作用域。
module testScope {
import Socket = SocketIOClient.Socket;
export class testClass {
socket: Socket;
constructor(){
this.socket = io.connect();
this.socket.on('test', () => this.testCallback()); // this is now testClass
}
testCallback(){
console.log(this);
}
}
}
您可以找到更多关于 this 工作原理的信息 here。
您可以找到有关箭头函数的更多信息 here。