1

Okay so in PHP we can call function as dynamic variables something like

$obj = new $class;
$obj->$myFoo($args);

But I am trying the same thing in Javascript but it's not working. The error is

Uncaught TypeError: foo is not a function 

My javascript code looks like this

function getId(arr){
    for(let i in arr){
        console.log("Function getId "+ arr[i]);
    }
}
function getMarker(arr){
    for(let i in arr){
        console.log("Function getMarker "+ arr[i]);
    }
}
const PAGEAPP = {
    processes:["getId","getMarker"],
    init:() => {
        for(let foo of PAGEAPP.processes){
            foo([1,2,3]);
        }
    },
}

Is there anyway I can access the same in Javascript.

Thank you in advance for your TIME :)

EDIT

This is what chrome showing

2
  • That is because your function names are strings inside the array instead of variables Commented Jan 8, 2020 at 7:30
  • Glad, I was able to help:) Commented Jan 8, 2020 at 7:49

1 Answer 1

3

Use function names rather than using strings

function getId(arr) {
  for (let i in arr) {
    console.log("Function getId " + arr[i]);
  }
}

function getMarker(arr) {
  for (let i in arr) {
    console.log("Function getMarker " + arr[i]);
  }
}
const PAGEAPP = {
  processes: [getId, getMarker],
  init: () => {
    for (let foo of PAGEAPP.processes) {
      foo([1, 2, 3]);

    }
  },
}

PAGEAPP.init()

Sign up to request clarification or add additional context in comments.

2 Comments

I know how to call it but My concern is after calling it, it's not working as supposed
It is doing what you are telling it to do. Run the code snippet. Also can you show us the expected output of your code?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.