Search code examples
javascriptbackbone.js

Execute a function from object value in javascript


I am trying to execute a function from each object key here is the code.

var testObj = { text: "this is text" , alltext: "this is all text" };

function text() {
    alert("this is test function for first value");
}

function alltext() {
    alert("this is test function for first second!");
}

for (item in testObj) { 
    console.log(item);
    item();
}

This gives me that item not a function.

Please visit this link to see the original code. I am using Backbone.js to create a form.The code is commented.

http://vianx.com/tst/script2.js

in this case gives that the "fieldConstructor" in not a function.


Solution

  • So I believe you are mistaken about how a dictionary works in javascript. The first value is a key and will always be a string value to do what you want you can do this

    var testObj = [[text, "this is text"] , [alltext, " thi is all text" ]];
    
    function text () {
      alert( "this is test function for first value");
    }
    
    function alltext () {
      alert( "this is test function for first second!" );
    }
    
    
    for ( index in testObj ) {
       
      console.log(index);
      testObj[index][0]();
    }