简体   繁体   English

Angular - 如何从对象内部调用函数

[英]Angular - How to call a function from inside an object

I'm wondering how can I call a function inside an object.我想知道如何在对象内部调用函数。 I created here a quick demo .我在这里创建了一个快速演示

Basically the idea is that I get some number from the user, I filter that number looking for the same value in my object and then I run a specific function.基本上这个想法是我从用户那里得到一些数字,我过滤这个数字以在我的对象中寻找相同的值,然后我运行一个特定的函数。

btw, maybe there is some nicer way to code that, webstorm suggested me to create functions outside my component idkw顺便说一句,也许有一些更好的编码方式,webstorm 建议我在组件 idkw 之外创建函数

Thanks for any suggestions :)感谢您的任何建议:)

You probably wanna have reference to the function rather than the function call in the Object.您可能想要引用函数而不是对象中的函数调用。 Something like setDate: currentDate rather than setDate: currentDate() .类似于setDate: currentDate而不是setDate: currentDate() Your code works after this change.您的代码在此更改后有效。

Improvements:改进:

Use in-place arrow functions in the object like so像这样在对象中使用就地箭头函数

datePeriods = [
  {
    name: "Currenty",
    value: 1,
    setDate: () => console.log(1)
  },
  {
    name: "Last",
    value: 2,
    setDate: () => console.log(2)
  },
  {
    name: "Custom",
    value: 3,
    setDate: () => console.log(3)
  }
];

Not exactly why they'd prefer using functions defined outside the scope.不完全是为什么他们更喜欢使用在范围之外定义的函数。 Unless you wish to reuse the function elsewhere, you could define the functions as inline arrow functions.除非您希望在其他地方重用该函数,否则您可以将这些函数定义为内联箭头函数。

datePeriods = [
  {
    name: "Currenty",
    value: 1,
    setDate: () => { console.log('current date') }
  },
  {
    name: "Last",
    value: 2,
    setDate: () => { console.log('last date') }
  },
  {
    name: "Custom",
    value: 3,
    setDate: () => { console.log('custom date') }
  }
];

And Array#filter is used to generate an array based on a certain condition. Array#filter用于根据特定条件生成数组。 Since you wish to only run the function when the condition is met and exit, you could use Array#some instead.由于您希望仅在满足条件并退出时运行该函数,因此您可以改用Array#some

onSelectedDate() {
  this.datePeriods.some(data => {
    if (this.selectedDate === data.value) {
      data.setDate();
      return true; // <-- skip the following iterations
    }
  });
}

I've updated your Stackblitz .我已经更新了你的Stackblitz


Note: While you could also use Array#forEach here, it'd continue to run even after the condition is met.注意:虽然您也可以在此处使用Array#forEach ,但即使满足条件,它也会继续运行。 Thus would lead to unnecessary iterations.因此会导致不必要的迭代。 Array#some on the other hand would short-circuit as soon the condition is met.另一方面,只要满足条件, Array#some就会短路。

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

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