【问题标题】:Typescript - Arrow Function with ParametersTypescript - 带参数的箭头函数
【发布时间】:2015-04-20 17:02:39
【问题描述】:

我是 Typescript 的新手,并试图将它引入我的一些东西,但我在使用一些范围和箭头函数时遇到了困难。

在 javascript 中,我的代码如下所示...

var model = params.model;

model.Prototypes.bind('change', function(e){
   // some code to execute when the event occurs
   model.set([some values]); // this performs an operation to the actual top level model
});

好的,所以这有两个问题。当我在 Typescript 中执行此操作时,我会这样做...

class ClassName {
   model: any;

   subscribe() {
      this.model.Prototypes.bind("change", function(e){
         // FIRST PROBLEM
         this.model ....
      });
   }
}

好的,所以这一直有效,直到标记的部分。 this.model 不再是我认为的引用,因为它是在函数的上下文中,而不是在“类”中。所以我做了一些挖掘并了解到我应该使用arrow function,因为这样可以保留上下文。

问题是,我无法想象如何在执行箭头函数的同时仍然传递我需要的参数,例如绑定事件的 change 值或 function(e) 部分。我只看到了根本不需要参数的示例。

【问题讨论】:

    标签: typescript arrow-functions


    【解决方案1】:

    箭头/lambda 语法如下所示:

    class ClassName {
       model: any;
    
       subscribe() {
          this.model.Prototypes.bind("change", e => {
             // FIRST PROBLEM
             this.model ....
          });
       }
    }
    

    如果您有多个参数,请使用以下格式:

    (p1, p2, p3) => { ... }
    

    希望这会有所帮助,

    【讨论】:

      猜你喜欢
      • 2019-12-17
      • 1970-01-01
      • 2023-01-08
      • 2017-10-02
      • 2021-07-22
      • 1970-01-01
      • 1970-01-01
      • 2022-01-17
      • 2019-05-07
      相关资源
      最近更新 更多