javascript – 在ES5的转换输出中,TypeScript应该在`_super`之前调用`this`?

我对扩展抽象类的所有子类使用依赖注入.

问题是,在抽象构造函数类中,我启动了一个我计划在子代中覆盖的方法,如果有必要的话.

我遇到的问题是我的注入依赖项在我从super启动的override类中不可见.

这是一个代码示例:

abstract class Base {

    constructor(view: string) {
        this._assemble();
    }

    protected _assemble(): void {
        console.log("abstract assembling for all base classes");
    }

}

class Example extends Base {

    constructor(view: string, private helper: Function) {
        super(view);
        console.log(this.helper);
    }

    public tryMe(): void {
        this._assemble();
    }

    protected _assemble(): void {
        super._assemble();
        // at first run this.helper will be undefined!
        console.log("example assembling", this.helper);
    }

}

let e = new Example("hoho", function () { return; })
console.log("So now i will try to reassemble...");
e.tryMe();

因此问题的核心是typescript将Example类转换为代码,如下所示:

function Example(view, helper) {
    _super.call(this, view);
    this.helper = helper;
    console.log(this.helper);
}

而不是这个:

function Example(view, helper) {
    this.helper = helper;
    _super.call(this, view);
    console.log(this.helper);
}

如您所见,如果我在_super之前将this.helper放在JavaScript中,this.helper将始终在_assemble中可见.即使super会调用_assemble函数.

但是默认情况下,在_super调用之后分配给它.所以如果超级类会调用汇编.第一次在Example中重写_assemble方法时不会显示它.

所以我的问题是……

这是一个错误吗?

要么

我不知道的是什么?

现在我修复了我的问题,只是从超类中删除_assemble,并始终从子进程调用它.但这只是错了.

Nota Bene:
这是编译的JavaScript代码与固定的JavaScript代码演示:

TypeScript通常输出:

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Base = (function () {
    function Base(view) {
        this._assemble();
    }
    Base.prototype._assemble = function () {
        document.write("<p>abstract assembling for all base classes</p>");
    };
    return Base;
}());
var Example = (function (_super) {
    __extends(Example, _super);
    function Example(view, helper) {
        _super.call(this, view);
        this.helper = helper;
        console.log(this.helper);
    }
    Example.prototype.tryMe = function () {
        this._assemble();
    };
    Example.prototype._assemble = function () {
        _super.prototype._assemble.call(this);
        // at first run this.helper will be undefined!
        document.write("<p>example assembling <b/>" + (this.helper) + "</b></p>");
    };
    return Example;
}(Base));
var e = new Example("test", function () { return "needle"; });
document.write("<p><i>So now i will try to reassemble...</i></p>");
e.tryMe();

TypeScript修复了javascript输出:

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Base = (function () {
    function Base(view) {
        this._assemble();
    }
    Base.prototype._assemble = function () {
        document.write("<p>abstract assembling for all base classes</p>");
    };
    return Base;
}());
var Example = (function (_super) {
    __extends(Example, _super);
    function Example(view, helper) {
        /**
         * Slight change, compiled assigning to this BEFORE _super.
         */
        this.helper = helper;
        _super.call(this, view);
        console.log(this.helper);
    }
    Example.prototype.tryMe = function () {
        this._assemble();
    };
    Example.prototype._assemble = function () {
        _super.prototype._assemble.call(this);
        // at first run this.helper will be undefined!
        document.write("<p>example assembling <b/>" + (this.helper) + "</b></p>");
    };
    return Example;
}(Base));
var e = new Example("test", function () { return "Needle"; });
document.write("<p><i>So now i will try to reassemble...</i></p>");
e.tryMe();

解决方法:

孩子不能在父母“存在”之前出生.

在Java和其他OOP语言中,必须在实例化当前对象之前调用super().

这是合乎逻辑的,因为孩子不能在父母之前出生.

TypeScript 2 now can have statements before super, if they are not using to this.

这是为什么在晚餐前不能使用这个问题的答案的一部分.

构造函数中使用的子覆盖方法应该纯粹存在于“父”资源上.

接触问题的下一部分是,父对象实际上在其子集未实例化的同时实际调用其子节点的覆盖.

这看起来很奇怪,因为孩子们没有实例化,但是父母构造函数调用了孩子们的方法……而且看起来不自然,就像未出生的孩子说“爸爸”一样.

See similar post about this issue.

但这是一种错误的思考方式.来自将在构造函数中使用的子项的覆盖,纯粹存在以更改子项的实例化方式.

父构造函数中使用的方法覆盖必须告诉您应该如何制作实例.来自那些可用于父级的资源,而不是来自不存在的实例所具有的资源.

鸭子打字原型和继承……

原型中的继承通常通过合成具有这种扩展功能的新原型来实现.

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};

从这个角度来看,没有“孩子”和“父母”这样,但有“套”,有点.只有在已存在的情况下,Set才能通过另一个集合进行扩展.这让我们:

Top-down and bottom-up design.

原型和鸭子打字工作采用自下而上的设计. OOP采用自顶向下设计.

在这种情况下如何解决这种奇怪的情况?

只是不要!通过学习和实施,利用OOP思想的力量!在这里如何成功:

> Composition over inheritance,重新考虑代码设计.将基类拆分为接口和类,可以将其实例传递给“child”类的构造函数,并通过实现声明的接口来组成所需的实例.
> Use static,但请注意,对于对象的所有实例,此更改都是相同的.

如果您仅将此用于依赖注入,则可以
>智能覆盖.

不要使用兄弟(“child”)实例中的额外资源,并创建一个将从构造函数中调用的额外方法.

下面的示例(请注意,这不违反LSP,因为在构造函数中只设置了__assembled一次):

abstract class Base {

    constructor(view: string) {
        this._assemble();
    }

    protected _assemble(): void {
        console.log("abstract assembling for all base classes");
    }

}

class Example extends Base {

    private __assembled: boolean = false;

    constructor(view: string, private helper: Function) {
        super(view);
        this._assemble_helper();
        this.__assembled = true;
    }

    public tryMe(): void {
        this._assemble();
    }

    protected _assemble(): void {
        super._assemble();
        // removed from here all extra resources
        // but run them when u need to assemble them again.
        if (this.__assembled) {
            this._assemble_helper();
        }
    }

    protected _assemble_helper(): void {
        // at first run this.helper will be undefined!
        console.log("example assembling", this.helper);
    }

}

let e = new Example("hoho", function () { return; })
console.log("So now i will try to reassemble...");
e.tryMe();

这是转换后的ES5结果:

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Base = (function () {
    function Base(view) {
        this._assemble();
    }
    Base.prototype._assemble = function () {
        console.log("abstract assembling for all base classes");
    };
    return Base;
}());
var Example = (function (_super) {
    __extends(Example, _super);
    function Example(view, helper) {
        var _this = _super.call(this, view) || this;
        _this.helper = helper;
        _this.__assembled = false;
        _this._assemble_helper();
        _this.__assembled = true;
        return _this;
    }
    Example.prototype.tryMe = function () {
        this._assemble();
    };
    Example.prototype._assemble = function () {
        _super.prototype._assemble.call(this);
        // removed from here all extra resources
        // but run them when u need to assemble them again.
        if (this.__assembled) {
            this._assemble_helper();
        }
    };
    Example.prototype._assemble_helper = function () {
        // at first run this.helper will be undefined!
        console.log("example assembling", this.helper);
    };
    return Example;
}(Base));
var e = new Example("hoho", function () { return; });
console.log("So now i will try to reassemble...");
e.tryMe();

原文地址:https://codeday.me/bug/20190828/1754832.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


我最大的一个关于TypeScript的问题是,它将原型的所有方法(无论访问修饰符)编译.例classExample{publicgetString():string{return"HelloWorld";}privategetNumber():number{return123;}}众所周知,访问修饰符仅在编译时检
我对React很新,我正在尝试理解子组件之间相互通信的简洁方法.在一个简单的组件中,我知道我可以使用props将数据传递给子节点,并让子节点的回调将数据传递回父组件.在稍微复杂的情况下,当我在父组件中有多个子组件时,子组件之间的通信会有点混乱.我不确定我应该为同级别的儿童组
我有一个非常简单的表单,我将用户电子邮件存储在组件的状态,并使用onChange函数更新状态.有一个奇怪的事情发生在我的onChange函数用函数更新状态时,我在键入时在控制台中得到两个错误.但是,如果我使用对象更新状态,则不会出现错误.我相信用函数更新是推荐的方法,所以我很想知道为
我发现接口非常有用,但由于内存问题我需要开始优化我的应用程序,我意识到我并不真正了解它们在内部如何工作.说我有interfaceFoo{bar:number}我用这种类型实例化一些变量:letx:Foo={bar:2}Q1:这会创建一个新对象吗?现在,假设我想改变bar的值.我这样做有两种
我得到了一个json响应并将其存储在mongodb中,但是我不需要的字段也进入了数据库,无论如何要剥离不道德的字段?interfaceTest{name:string};consttemp:Test=JSON.parse('{"name":"someName","age":20}')asTest;console.log(temp);输出:{name:'someName
我试图使用loadsh从以下数组中获取唯一类别,[{"listingId":"p106a904a-b8c6-4d2d-a364-0d21e3505010","section":"section1","category":"VIPPASS","type":"paper","availableTi
我有以下测试用例:it("shouldpassthetest",asyncfunction(done){awaitasyncFunction();true.should.eq(true);done();});运行它断言:Error:Resolutionmethodisoverspecified.SpecifyacallbackorreturnaPromise;n
我正在一个有角度的2cli项目中工作,我必须创建一个插件的定义,因为它不存在它的类型.这个插件取决于已经自己输入的主库,它可以工作.无论如何,我有两个文件主要的一个图书馆类型文件AexportclassAextendsB{constructor(...);methodX():void;}我需要为我的
我有三元操作的问题:leta=undefined?"Defined!":"DefinitelyUndefined",b=abc?"Defined!":"DefinitelyUndefined",//ReferenceErrorc=(abc!==undefined)?"Defined!":"DefinitelyUndefin
下面的代码片段是30秒的代码网站.这是一个初学者的例子,令人尴尬地让我难过.为什么这样:constcurrentURL=()=>window.location.href;什么时候可以这样做?constcurrentURL=window.location.href;解决方法:第一个将currentURL设置为一个求值为window.location.href的
我是TypeScript和AngularJS的新手,我正在尝试从我的API转换日期,例如:"8/22/2015"…到ISO日期.将日期正确反序列化为Date类型的TypeScript属性.但是,当我尝试以下命令时(在typescript中,this.dateDisplay的类型为string)this.dateDisplay=formats.dateTimeValue.toISOString
我的名为myEmployees的数组中有5个名字,但是当我运行代码时,它只打印出其中的3个.我相信这种情况正在发生,因为脚本中的for循环覆盖了它在HTML文档中编写的前一行.我怎样才能解决这个问题?YearlyBulletinBoardAnnouncements!CongratulationstoTaylor,youhavebeenheref
我看到有一种方法可以在摩纳哥编辑器中设置scrolltop.如何滚动到特定行而不是特定像素?解决方法:如在文档中:https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.icodeeditor.html滚动到顶部,在px中:editor.setScrollPosition({scrollTop:0});滚动到特定
在从同一个类继承的一个数组中收集各种不同的对象时,如何在TypeScript中设置一个优等的类,以便TypeScript不显示错误?我正在尝试这样:interfaceIVehicle{modelName:string}interfaceICarextendsIVehicle{numberOfDoors:number,isDropTop:boolean}inte
什么是TypescriptTypeScript是一种由微软开发的自由和开源的编程语言,它是JavaScript的一个超集,扩展了JavaScript的语法。作者是安德斯大爷,Delphi、C#之父(你大爷永远是你大爷)。把弱类型语言改成了强类型语言,拥有了静态类型安全检查,IDE智能提示和追踪,代码重构简单、可读性
0.系列文章1.使用Typescript重构axios(一)——写在最前面2.使用Typescript重构axios(二)——项目起手,跑通流程3.使用Typescript重构axios(三)——实现基础功能:处理get请求url参数4.使用Typescript重构axios(四)——实现基础功能:处理post请求参数5.使用Typescript重构axios(五
1.1Typescript介绍1.TypeScript是由微软开发的一款开源的编程语言,像后端java、C#这样的面向对象语言可以让js开发大型企业项目。2.TypeScript是Javascript的超级,遵循最新的ES6、Es5规范(相当于包含了es6、es5的语法)。TypeScript扩展了JavaScript的语法。3.最新的Vu
0.系列文章1.使用Typescript重构axios(一)——写在最前面2.使用Typescript重构axios(二)——项目起手,跑通流程3.使用Typescript重构axios(三)——实现基础功能:处理get请求url参数4.使用Typescript重构axios(四)——实现基础功能:处理post请求参数5.使用Typescript重构axios(
webpack.config.jsconstpath=require('path');constCopyWebpackPlugin=require('copy-webpack-plugin');constExtractTextPlugin=require('extract-text-webpack-plugin');const{CleanWebpackPlugin}=require('clean-webpac
我在这篇ECMAScriptpage上读到“class”是JavaScript的一部分.在这个关于TypeScript的页面上,我看到’class’也可以在Typescript中找到.我的问题是,开发未来JavaScript应用程序的正确方法是利用(a)JavaScript中的面向对象功能以及EMACScript7.0中可用的功能或(b)使用TypeScript