简体   繁体   English

在数组中的对象上调用方法的功能方法

[英]Functional way to call method on objects in an Array

I would like to call a method which takes no arguments and returns nothing, on each Object in an Array of homogenous objects, without using a for loop like this: 我想在不使用for循环的情况下,在同构对象数组中的每个对象上调用不带参数且不返回任何内容的方法,而无需使用如下的for循环:

for (let i = 0; i < list.length; i++) {
    list[i].someMethod();
}

I've looked at using Array.forEach (and discounted Array.map ), tried passing the method name as a string, and by using call and grabbing the prototype method from one of the objects, as well as reading around the area on various websites. 我研究过使用Array.forEach (和打折的Array.map ),尝试将方法名称作为字符串传递,并通过使用call并从其中一个对象获取原型方法,以及在各种区域中进行读取网站。

I don't see a clean way to do it, such that every invocation is bound to the correct this . 我看不到一种干净的方法,这样每次调用都必须绑定到正确的this Can someone point out what blindingly obvious technique I've overlooked? 有人可以指出我忽略了哪些令人眼花obvious乱的明显技巧吗?

使用匿名函数作为forEach的回调,并像往常一样调用该方法: list.forEach(function(o) { o.someMethod(); });

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

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