【问题标题】:Typescript: TS2496: The 'arguments' object cannot be referenced in an arrow function in ES3 and ES5. Consider using a standard function expression打字稿:TS2496:不能在 ES3 和 ES5 的箭头函数中引用“参数”对象。考虑使用标准函数表达式
【发布时间】:2016-06-28 13:34:23
【问题描述】:

我按照http://www.html5rocks.com/en/tutorials/frameworks/angular-websockets/ 之类的教程在我的 node.js 服务器和 angular.js 客户端中实现了 socket.io,一切正常。

但是,客户端,Typescript 显示以下编译错误:

TS2496: The 'arguments' object cannot be referenced in an arrow function in ES3 and ES5. Consider using a standard function expression.

关于以下服务代码:

on(eventName:string, callback) {
  this.socket.on(eventName, () => {
    var args = arguments; // <-- here the compilation error
    this.$rootScope.$apply(() => {
      callback.apply(this.socket, args);
    });
  });
}

emit(eventName:string, data, callback?) {
  this.socket.emit(eventName, data, () => {
    var args = arguments; // <-- here the compilation error
    this.$rootScope.$apply(() => {
      if (callback) {
        callback.apply(this.socket, args);
      }
    });
  });
}

我尝试了不同的解决方案,例如 https://github.com/Microsoft/TypeScript/issues/1609 第一篇文章中描述的解决方案,它修复了编译但破坏了 socket.io “on”功能(不再解释 json 对象)。

知道如何修复或忽略此打字稿编译错误吗?

【问题讨论】:

    标签: angularjs typescript socket.io


    【解决方案1】:

    另一种可能性是使用rest parameter 而不是arguments

    on(eventName:string, callback) {
      this.socket.on(eventName, (...args) => {
        this.$rootScope.$apply(() => {
          callback.apply(this.socket, args);
        });
      });
    }
    

    【讨论】:

    • 从给定的链接中研究了一些关于休息参数的信息,然后这对我有用。干杯!
    • 非常好的解决方案!我一直在寻找 function 声明的替代方案,因为后者在我的 Angular 项目中总是被解释得太早,导致服务引用无效。
    【解决方案2】:

    箭头函数表达式是正则函数表达式的语法紧凑替代方案,尽管它自己没有绑定到 thisargumentssupernew.target 关键字。

    但您可以使用function 代替() =&gt;

    on(eventName:string, callback) {
        var self = this;
        this.socket.on(eventName, function() {
            var args = arguments;
            self.$rootScope.$apply(() => {
                callback.apply(self.socket, args);
            });
        });
    }
    

    【讨论】:

    • 值得一提的是,箭头函数不绑定自己的 this 参数,而是使用父闭包中的参数。 MDN链接developer.mozilla.org/en/docs/Web/JavaScript/Reference/…
    • 这就是你不能使用它们的原因。
    • 在此处发帖之前,我也尝试使用“function”而不是“()=>”,但我错过了 self 而不是 this。这个解决方案就像一个魅力,谢谢你的快速回答
    猜你喜欢
    • 1970-01-01
    • 2018-09-30
    • 1970-01-01
    • 1970-01-01
    • 2021-06-28
    • 2016-08-26
    • 2017-01-04
    • 2019-09-27
    • 2019-04-29
    相关资源
    最近更新 更多