-2

How do you loop through a javascript object and if the object property you want happens to be a function, execute that function?
For example, the below code loops through an object and outputs its property based on some input. In the example command.first outputs fine, but when trying to output command.clear it returns the actual function as a string.
Output: "function(){ document.getElementById("output").innerHTML = "";"

var command = new Object();

command.first = "First string";

command.clear = function() { 
    document.getElementById("output").innerHTML = "someStuff"; 
};

for(var key in command) {

    if(key == input) {

        document.getElementById("output").innerHTML = command[input];

    }

}
Hezerac
  • 334
  • 1
  • 5
  • 20

2 Answers2

1

Check if a certain value is instance of Function object. Any function (including arrow functions) is always an instance of Function:

var command = new Object();

command.first = "First string";
command.clear = function() { 
    return "someStuff"; 
};

for(var key in command) {
    if(key == input) {
        document.getElementById("output").innerHTML = command[input] instanceof Function ? command[input]() : command[input];
    }
}

You can see that clear doesn't change the innerHTML attribute of element directly. It just returns a string, and this string is assigned as value of innerHTML property inside the for loop.

rishat
  • 8,206
  • 4
  • 44
  • 69
  • 1
    I find it even easier to use `x typeof === "function"` instead of checking the prototype chain. – VLAZ Sep 11 '16 at 21:15
  • Why not use strict comparison ? – mike_hornbeck Sep 11 '16 at 21:29
  • There's [an answer about that](http://stackoverflow.com/a/6625960/1287643), and although I don't see any difference in this particular case, looks like you're right and generally it's better to check if a certain reference is a function using `typeof`. – rishat Sep 11 '16 at 21:44
  • So how to use typeof here? `if(typeof command[input] === "function) {document.getElementById("output").innerHTML = command[input]();}` This outputs `undefined`. – Hezerac Sep 11 '16 at 21:59
  • Because your function `command.clear` doesn't return anything, therefore it returns `undefined`. – rishat Sep 11 '16 at 22:00
  • I updated the answer: `clean` has to return a string, not change `innerHTML` attribute directly. – rishat Sep 11 '16 at 22:02
1

You don't have to set innerHTML of a function that does not return anything and still you have to include '()' for your function for it to be executed. Use this way

var command = new Object();
command.first = "First string";
command.clear = function() {     
document.getElementById( "output").innerHTML= "someStuff";
};
for ( var key in command) {
if (key == input) {
if(typeof(command[input])=="function"){
command[input]()
  }
else{
document.getElementById( "output" ).innerHTML= command[input]
 }
 }
 }
Taiti
  • 375
  • 2
  • 6