【问题标题】:Is the value of 'this' in switch statement in Typescript 1.6.2 and atom-typescript emited incorrectly?Typescript 1.6.2 和 atom-typescript 的 switch 语句中“this”的值是否错误地发出?
【发布时间】:2015-11-14 16:50:55
【问题描述】:

我有一些 Typescript 代码,看起来像这样:

class Test {
    private userId: string
    constructor() {
      this.userId = 'test'
    }
    test() {
      return new Promise((resolve, reject) => {
        let sharing = 'private'
        console.log("before switch this.userId", this.userId);
        switch (sharing) {
          case "private":
            resolve(this.userId);
            break;
        }
      })
    }
}

如果我在 the Typescript playground 中编辑它,则会按预期发出以下 Javascript 代码:

var Test = (function () {
  function Test() {
    this.userId = 'test';
  }
  Test.prototype.test = function () {
    var _this = this;
    return new Promise(function (resolve, reject) {
        var sharing = 'private';
        console.log("before switch this.userId", _this.userId);
        switch (sharing) {
            case "private":
                resolve(_this.userId);
                break;
        }
    });
  };
  return Test;
})();

但是,如果我在已安装的 Atom 编辑器中编辑相同的代码,则会发出:

var Test = (function () {
  function Test() {
    this.userId = 'test';
  }
  Test.prototype.test = function () {
    var _this = this;
    return new Promise(function (resolve, reject) {
        var sharing = 'private';
        console.log("before switch this.userId", _this.userId);
        switch (sharing) {
            case "private":
                resolve(this.userId); // This resolve is missing a _
                break;
        }
    });
  };
  return Test;
})();

不同之处在于解析语句向下 12 行。正在解决的是this.userId,而不是_this.userId

我正在运行新安装:

  • Atom 1.1.0
  • 原子打字稿 7.8.0
  • Ubuntu 15.10
  • typescript 1.6.2 与 npm 一起安装

【问题讨论】:

    标签: typescript atom-editor


    【解决方案1】:

    这是 TypeScript 中的一个问题,两天前已修复:https://github.com/Microsoft/TypeScript/issues/5637

    刚刚在 atom-typescript 中修复https://github.com/TypeStrong/atom-typescript/releases/tag/v7.10.0

    【讨论】:

      【解决方案2】:

      我在 Webstorm 11 上用 TS 1.6.2 发射 ES5 和 commonjs 模块对你的代码进行了测试:发射的 JS 代码是正确的。

      要编译,我必须声明 Promise

      declare class Promise {
           constructor(callback: (resolve:Function, reject:Function) => void);
      }
      

      所以我怀疑编译器是罪魁祸首,尽管我不明白为什么 atom-typescript 插件会影响发出的代码。联系开发者(Basarat Ali Syed)?

      Promise 是如何声明的?

      【讨论】:

      • 感谢您的意见。声明 Promise 会删除错误,但不会影响发出的 Javascript。我知道巴萨拉特在这里闲逛,所以希望他能看到这一点。我将更改标题以表明问题仅在 atom-typescript 中很明显。
      • 我已经在 VS Code 中测试了代码,它被正确发出,所以它看起来确实是 Atom 特定的
      猜你喜欢
      • 1970-01-01
      • 2020-01-14
      • 1970-01-01
      • 1970-01-01
      • 2021-07-11
      • 1970-01-01
      • 1970-01-01
      • 2020-06-21
      • 2017-11-01
      相关资源
      最近更新 更多