Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/459.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 抽象方法TypeScript的怪异行为_Javascript_Typescript - Fatal编程技术网

Javascript 抽象方法TypeScript的怪异行为

Javascript 抽象方法TypeScript的怪异行为,javascript,typescript,Javascript,Typescript,我使用带有参考“atmosphere.d.ts”的typescript。我用抽象方法触发了一个奇怪的行为,导致了错误: TypeError:this.protectedMethod不是函数 以下是typescript代码: /// <reference path="../atmosphere.d.ts" /> import Request = Atmosphere.Request; abstract class AbstractRequest { // The atmos

我使用带有参考“atmosphere.d.ts”的typescript。我用抽象方法触发了一个奇怪的行为,导致了错误:

TypeError:this.protectedMethod不是函数

以下是typescript代码:

/// <reference path="../atmosphere.d.ts" />
import Request = Atmosphere.Request;

abstract class AbstractRequest {

    // The atmosphere request
    protected socket: Request;

    // Here we initialize the socket
    protected init(url: string): void {
        this.socket = {
            url                 : "http://localhost:9000/" + url,
            contentType         : "application/json",
            transport           : "websocket" ,
            fallbackTransport   : "long-polling"
        };

        /* SOME CODE */

        this.socket.onOpen = function(response) {
            this.protectedMethod();
        };
    }

    // Some protected method called in this.socket.onOpen
    protected abstract protectedMethod(): void;
}

class Registration extends AbstractRequest {

    // Implementation of the abstract method
    protected protectedMethod(): void {
        console.log("hello");
    }
}
当我实现“onOpen”方法时,我不能从“socket”变量调用抽象方法(也可能是非抽象的?)。目前我找到的唯一解决方法是实例化一个全局变量

var registration = new Registration();
然后:

this.socket.onOpen = function(response) {
    registration.protectedMethod;
};
有了这个解决方法,我必须定义“protectedMethod”public。是否有对此行为的解释,以及解决方法/修复方法?顺便说一句,我使用typescript 1.8.10

谢谢,这是由于:

调用
new AbstractRequest().socket.onOpen()
时,此
将绑定到
socket
而不是
new AbstractRequest()
指向点左侧的任何对象)

您可以使用箭头函数来解决此问题。在arrow functions
中,此
绑定到定义它的上下文,而不是运行它的上下文:

this.socket.onOpen = response => {
    this.protectedMethod();
};

我相信这实际上是对受保护方法的期望。他们只接触自己的类和子类非常有趣,谢谢你的提示和解释!没问题。如果您想了解更多细节,MDN是一个很好的来源。但这不是一个bug吗?因为它超出了范围,所以报告说该方法不存在?更多的是缺少的特性。我们已经做了一些工作来实现一个
--noimplicitt这个
标志,它将检测这个bug。看见
var AbstractRequest = (function () {
    function AbstractRequest() { }
    AbstractRequest.prototype.init = function (url) {
        // ...snip...
        this.socket.onOpen = function (response) {
            this.protectedMethod();
        };
    };
    return AbstractRequest;
}());
this.socket.onOpen = response => {
    this.protectedMethod();
};