繁体   English   中英

如何在JS / TS功能编程中将箭头功能用作属性

[英]How to use an arrow function as a property in JS/TS functional programming

假设我将使用TypeA :一些参数,以及TypeB :类本身的类型来构造函数类的构造函数,我可以使用

functionName(argument: TypeA): TypeB {
    this.property = argument;
    return this;
  }

但不能使用

property: (argument: TypeA): TypeB => ({
    property: argument,
    ...
  })

我明白这是由于在差异this时候我用一个箭头功能和正常功能。

然后,如何使用箭头函数,该箭头函数将与正常功能的第一种情况一样工作?

例:

import personConst from './personConst';
// const personConst: { [key: string]: UnitBase } = {
//   brah: {
//     name: "Thomas",
//     age: 25,
//     gender: "male"
//   },
//   hoge: {
//     name: "Sarah",
//     age: 29,
//     gender: "female"
//   },
//   ...
// }

import { PersonBase } from './PersonBase';
// export interface UnitBase {
//   name: string;
//   age: number;
//   gender: string;
// }


interface Person extends PersonBase {
  income: number;
  zip: number;
  setIncome(newIncome: number): this;
  setZip(newZip: number): this;
}

const person = (key: string): Person => ({
  income: 50000,
  zip: 50000,
  setIncome: (newHp: number): Person => ({
    income: newIncome,
    ... // Error: Expression expected.
  }),
  setZip(newZip: number): Person {
    this.zip = newZip;
    return this; // OK
  },
  ...personConst[key]
});

export default person;

我不确定我是否理解您的问题,但是如果您想使用this上下文,则不应直接使用箭头函数x => y 相反,您可以使用更冗长的匿名函数(function(x){ return y })语法:

const person = (key: string): Person => ({
  income: 50000,
  zip: 50000,
  setIncome: function(newIncome: number): Person { // anonymous function
    return {
      ...this, 
      income: newIncome
    };
  },
  setZip(newZip: number): Person {
    this.zip = newZip;
    return this; // OK
  },
  ...personConst[key]
});

认为这就像您想要的那样:

const thomas = person("brah");

console.log(thomas.zip); // 50000
thomas.setZip(10301);
console.log(thomas.zip); // 10301

console.log(thomas.income); // 50000
thomas.setIncome(100000);
console.log(thomas.income); // 50000
const newThomas = thomas.setIncome(100000);
console.log(newThomas.income); // 100000

但是我不能从你的问题中分辨出来。 无论如何,希望能有所帮助; 祝好运!

链接到代码

您不能在任何地方使用粗箭头。 它最常用的:-使用粗箭头(=>),我们无需使用'function'关键字。 它的匿名函数-为避免在构造函数中进行绑定,可以使用(=>)-对于doSomething(){}之类的函数,您不能在此处使用粗箭头。 但是,例如:function(){},您可以在此处使用lambda。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM