【问题标题】:TypeScript should assign to `this` before `_super` call in transpiled output for ES5?TypeScript 应该在 ES5 的转译输出中调用 _super 之前分配给 this?
【发布时间】:2017-04-22 14:09:52
【问题描述】:

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

如果需要,我在抽象构造函数类中启动了一个我计划在其子级中覆盖的方法的问题。

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

下面是代码示例:

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);
}

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

但默认分配给它是在_super 调用之后。所以如果super 类将调用汇编。首次在示例中覆盖的_assemble 方法中将不可见。

所以我的问题是......

这是一个错误吗?

我不知道什么?

现在我解决了我的问题,只是从 super 类中删除了 _assemble,并且总是从孩子那里调用它。但这感觉不对。

注意事项: 这是编译后的 JavaScript 代码 vs 固定的 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();

【问题讨论】:

  • 您正在谈论将被转译为 ES5 的代码。我说的是转译结果的代码,即 ES5。请尝试编译我提供的 TypeScript 示例,并查看 private helper 在超类中不可见。\
  • 它被编译到 ES5 的方式应该与 ES6 类的工作方式相同(为什么要不然呢?)。在 ES6 中,不允许在调用基类构造函数之前使用this
  • @artem 因此,在这种情况下,以应该在 ES6 中工作的方式转换为 ES5 不是一种选择。我认为在 TS => ES5 中,它应该在super 之前将所有private, public, protected 转换为构造参数。其余的应该照常进行。

标签: javascript typescript transpiler


【解决方案1】:

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

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

这是合乎逻辑的,因为child cannot be born before parent

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

这是为什么晚餐前不能使用this 的部分答案。


在构造函数中使用的子覆盖方法应该完全存在于“父”资源中。

问题涉及的下一部分是,parent 对象实际上在此子对象根本未实例化的同时调用其子对象 assemble 的覆盖。

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

See similar post about this issue.

但这样思考是错误的。将在构造函数中使用的孩子的覆盖,纯粹是为了改变您的孩子将被实例化的方式。

父构造函数中使用的方法覆盖必须说明应该如何制作您的实例。来自父级可用的资源,而不是来自不存在的实例拥有的资源。


Duck 类型原型和继承...

原型中的继承通常通过将新原型与extend 类似的功能组合在一起来实现。

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 __());
};

从这个角度来看,没有“孩子”和“父母”本身,但有“集合”之类的。只有当集合已经存在时,它才能被另一个集合扩展。这使我们:

Top-down and bottom-up design.

原型和鸭式打字采用自下而上的设计。自顶向下设计中的 OOP。


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

别这样!通过学习和实施,利用 OOP 思想的力量!这里如何成功:

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

    如果你只将它用于依赖注入就可以了

  • 智能覆盖。

    不要使用来自同级(“子”)实例的额外资源,并创建一个自己的额外方法,该方法将从构造函数中调用。

    下面的例子(请注意,这并不违反 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();

【讨论】:

    猜你喜欢
    • 2014-12-02
    • 2021-11-06
    • 2014-07-31
    • 1970-01-01
    • 2017-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-15
    相关资源
    最近更新 更多