interface IMySocks {
start(): void;
}
declare var $;
class MySocks implements IMySocks {
private address: string;
private protocols = [];
private mySock: WebSocket;
start() {
this.mySock = new WebSocket(this.address, this.protocols);
this.mySock.onclose = this.onclose;
this.mySock.onopen = this.onopen;
this.mySock.onerror = this.onerror;
this.mySock.onmessage = this.onmessage;
}
private onopen(): void {
this.sendIt();
console.debug("OPEN");
}
private sendIt() {
.....}
var my: IMySocks = new MySocks(); my.start();
所以这样的类就来到了Error的主题中。智能感知和编译在 typescript 文件中没有发现错误。我正在使用 VS2012 Ultimate update 2 和 typescript 1.0。怎么了?
当我调用 this.sendIt(); 时会出现问题
最佳答案
与 C# 等其他一些编程语言不同,C# 会自动将 this
上下文保留为您想要的内容,而 JavaScript 中的 this
上下文有点不同。欲了解更多详细信息,您可以阅读this 。
您也可以考虑使用 ES5 中提供的 bind
来使用更典型的 JavaScript 方法( Mozilla docs/MSDN docs ),而不是创建闭包来捕获 this
:
this.mySock.onclose = this.onclose.bind(this);
bind
返回一个绑定(bind)到所提供的 this
上下文(或您想要的任何上下文)的函数。该函数 (onclose
) 将在运行时使用正确的上下文集进行调用。
关于typescript - 0x800a01b6 - JavaScript 运行时错误 : Object doesn't support property or method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23883568/