Hezerac Hezerac - 2 months ago 19
Javascript Question

javascript object traversal with method property

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];

}

}

Answer

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]
 }
 }
 }
Comments