Имя динамической функции в javascript?

Повышение попытки:: xtime и timed_wait ()

имеют точность наносекунды.

77
задан Tim Cooper 6 May 2011 в 00:15
поделиться

1 ответ

Я боролся много с этой проблемой. решение для @Albin работало как очарование при разработке, но оно не работало, когда я изменил его на производство. После некоторой отладки я понял, как достигнуть того, в чем я нуждался. Я использую ES6 с CRA (create-react-app), что означает, что он связывается Webpack.

Позволяет, говорят, что у Вас есть файл, который экспортирует функции, в которых Вы нуждаетесь:

myFunctions.js

export function setItem(params) {
  // ...
}

export function setUser(params) {
  // ...
}

export function setPost(params) {
  // ...
}

export function setReply(params) {
  // ...
}

И Вы должны динамично вызвать эти функции в другом месте:

myApiCalls.js

import * as myFunctions from 'path_to/myFunctions';
/* note that myFunctions is imported as an array,
 * which means its elements can be easily accessed
 * using an index. You can console.log(myFunctions).
 */

function accessMyFunctions(res) {
  // lets say it receives an API response
  if (res.status === 200 && res.data) {
    const { data } = res;
    // I want to read all properties in data object and 
    // call a function based on properties names.
    for (const key in data) {
      if (data.hasOwnProperty(key)) {
        // you can skip some properties that are usually embedded in
        // a normal response
        if (key !== 'success' && key !== 'msg') {
          // I'm using a function to capitalize the key, which is
          // used to dynamically create the function's name I need.
          // Note that it does not create the function, it's just a
          // way to access the desired index on myFunctions array.
          const name = `set${capitalizeFirstLetter(key)}`;
          // surround it with try/catch, otherwise all unexpected properties in
          // data object will break your code.
          try {
            // finally, use it.
            myFunctions[name](data[key]);
          } catch (error) {
            console.log(name, 'does not exist');
            console.log(error);
          }
        }
      }
    }
  }
}

0
ответ дан 24 November 2019 в 10:50
поделиться
Другие вопросы по тегам:

Похожие вопросы: