我怎样才能将原型功能作为参数?

时间:2017-11-20 10:54:00

标签: javascript ecmascript-6 babeljs

让我们说:

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

MapMePls('Hello World!', toLowerCase);

func可以是String的任何原型函数。

1 个答案:

答案 0 :(得分:1)

您可以将函数的名称作为string传递,并使用[]语法来访问它。还要添加一个检查,以确保传递的名称是实际功能名称

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'));