简体   繁体   English

如何将原型功能用作参数?

[英]How can I have prototype function as parameters?

Let say: 说:

function MapMePls (str, func, ...args) {
  return str.func(...args);
}

MapMePls('Hello World!', toLowerCase);

The func can be any prototype functions from String . func可以是String任何原型函数。

You can pass the name of the function as string and use [] syntax to access it. 您可以将函数名称作为string传递,并使用[]语法进行访问。 Also add a checking to be sure that the passed name is an actual function name . 还添加检查以确保传递的名称是实际的函数名称

 function MapMePls (str, func, ...args) { if(!str[func] || typeof str[func] !== 'function') { throw new Error('function does not exist'); } return str[func](...args); } console.log(MapMePls('Hello World!', 'toLowerCase')); 

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

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