typescript - 0x800a01b6 - JavaScript 运行时错误 : Object doesn't support property or method

标签 typescript

    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/

相关文章:

typescript - "Variable is used before being assigned"(TS2454) 没有帮助的模式

Angular 2 -> 如何使用 FormGroup 隐藏控件

javascript - 重命名 Typescript 文件

javascript - to$q 的 typescript 定义文件

angular - 在登录页面请求之前检查 session

javascript - kendo ui Typescript this 关键字

javascript - Jest --runTestsByPath 两个或多个不同的路径

javascript - Jest/Enzyme/JSDOM document.body.createTextRange 不是函数

typescript - 在受约束的通用函数中混淆 "[ts] Type ... is not assignable to type [2322]"错误

typescript - 为什么这段代码不能用 typescript 编译?