【问题标题】:How to force typescript to capture "this"?如何强制打字稿捕捉“这个”?
【发布时间】:2021-04-29 22:46:02
【问题描述】:

假设我有以下:

module Test {
    export class Foo {
        public A = 123;
        public GetA() {
            return this.A;
        }
    }
}

编译成

var Test;
(function (Test) {
    var Foo = (function () {
        function Foo() {
            this.A = 123;
        }
        Foo.prototype.GetA = function () {
            return this.A;
        };
        return Foo;
    })();
    Test.Foo = Foo;
})(Test || (Test = {}));

这一切都很好,但我有一个案例,GetA 将在不同对象的上下文中运行,所以我需要在闭包中捕获“this”。

所以基本上我需要这个JS:

function Foo() {
    this.A = 123;
    var self = this;
    this.GetA = function () {
        return self.A;
    }
}

有没有办法通过 typescript 的类语义来实现这一点,我应该回退到纯 JS 吗?

【问题讨论】:

  • 你如何在不同对象的上下文中执行GetA
  • 大多数情况下,当您将函数作为回调提供时(例如,promise 回调、事件等......)

标签: typescript


【解决方案1】:
module Test {
    export class Foo {
        public A = 123;
        public GetA = ()=>{return this.A;}
    }
}

请试一试。这是生成的javascript:

        var Test;
        (function (Test) {
            var Foo = (function () {
                function Foo() {
                    var _this = this;
                    this.A = 123;
                    this.GetA = function () {
                        return _this.A;
                    };
                }
                return Foo;
            })();
            Test.Foo = Foo;
        })(Test || (Test = {}));

【讨论】:

  • prototype 上不再有该功能,这可能会使该解决方案不太理想。
  • 你真的需要它作为原型吗,预期的javascript与生成的几乎相同。
  • 没有原型 super.GetA 将无法工作。正如 WiredPrairie 建议的那样提及会很有用
【解决方案2】:

对于那些遇到此页面的人,显然 TypeScript 人在这里解决了这个问题: https://github.com/Microsoft/TypeScript/wiki/'this'-in-TypeScript

【讨论】:

    猜你喜欢
    • 2017-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-03
    • 2014-07-04
    • 1970-01-01
    • 2019-11-06
    • 2018-03-22
    相关资源
    最近更新 更多