【问题标题】:Lodash: apply class instance method if instance is not null or undefinedLodash:如果实例不为空或未定义,则应用类实例方法
【发布时间】:2021-02-08 13:30:00
【问题描述】:

假设我们有以下示例:

class Person {
  surname: string;
  firstname: string;

  getFullName(separator: string) {
    return this.surname + separator + this.firstname;
  }
}

const person = ...

const fullName = _.ifNotNull(person, value => value.getFullName('-'));

是否有与Lodash 中的ifNotNull 函数等效的函数,它仅在对象参数不为空或未定义时应用来自对象参数的方法?

【问题讨论】:

  • 你不需要lodash。 person?.getFullName('-')
  • @MoshFeu 你的意思是person?person.getFullName('-'):default ? 它认为使用像_.ifNotNull这样的函数可以更干净
  • 不,他的意思是person?.getFullName,它叫Optional Chaining。尝试使用函数来实现已经内置的功能似乎毫无意义。它看起来不干净,看起来像是在浪费时间。
  • @DaneBrouwer 好吧,我正在使用需要 TypeScript >=3.4.0 和

标签: typescript lodash


【解决方案1】:

你可以使用 Lodash

事实上,Lodash 已经有了你要找的功能,它叫做_.invoke。在上面的示例中,您可以编写:

const fullName = _.invoke(person, "getFullName", "-");

它会按预期工作。那么,_.invoke 是如何工作的呢?

  • _.invoke 具有以下签名:_.invoke(object, path, [args])。它在对象内部的路径(可以是嵌套路径,也可以是方法名称)处调用方法,this 绑定到对象。

我可以在浏览器中快速尝试一下吗?

当然!我制作了一个 Codepen,您可以在其中尝试此方法和其他方法,直接在浏览器中执行相同的操作。只记得打开浏览器控制台查看测试结果!这是链接,你可以在testcase1a()testcase1b()找到_.invoke

https://codepen.io/jhack_jos/pen/ExNVbWp

上面的表达式如何解决?

  1. 如果person 未定义或person 没有名为getFullName 的方法,则表达式_.invoke(person, "getFullName", "-"); 解析如下:
    //STEP 1
    const fullName = _.invoke(person, "getFullName", "-");

    //STEP 2
    const fullName = undefined;
  1. 如果定义了person,并且有一个getFullName 方法:
    //STEP 1
    const fullName = _.invoke(person, "getFullName", "-");

    //STEP 2
    const fullName = person.getFullName("-");

    //STEP 3
    const fullName = "surname-firstname";

警告

如果person 的属性不是名为getFullName 的方法,则会出现运行时错误!!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-20
    • 2021-07-17
    • 2017-08-28
    • 2019-08-30
    • 2018-09-05
    • 2019-12-16
    相关资源
    最近更新 更多