• Say I have an object with a number of properties of the function type.

    
    var obj={}
    obj.test1=function(a){console.log("test1­ called"+a);};
    obj.test2=function(a){console.log("test2­ called"+a);};
    
    

    Now, I want a function that takes a string and an argument. If the object has that property, call the function with the argument. If not, return an error. Is there any way to do this without eval, or making scratch variables that waste memory?

    function jstest(funname,argument)
    if (obj.hasOwnProperty(funname))
    			{
    				console.log(obj. //what do I do here? if I call jstest("test1",a), I want this line to do console.log(obj.test1(a)), if called with "test2" instead, obj.test2(a), etc. How do I go between 
    			} else { //handle error }
    
    

    The context is that I am writing a webserver code for Espruino which will serve most file extensions off the SD card, but if it sees certain extensions (indicating that the page should be dynamically generated), it will see if there's a function to generate that page, and call it if so.

    My thinking was that I'd have an object like this, so if I got a request for status.json, I'd call the jsonPage.status() function, if I got a request for asdf.json, I'd call jsonPage.asdf() - or if that didn't exist, I'd return a 404. But what I'm puzzled about is how to call the function without using eval(), which I've been criticized for overusing in the past - I have no idea how else to do it! Even using eval is really awkward, since I'd need to do var temp=eval("jsonPage."+funname); temp(argument); - this means making a copy, which is wasteful of memory...

    
    jsonPage = {};
    jsonPage.status=function(path,query){ret­urn "status goes here";};
    jsonPage.history=function(path,query){re­turn "history goes here";};
    
    

    There's got to be a simple way to do this, but I just don't know what it is, nor what to call this to get results from google.

About

Avatar for DrAzzy @DrAzzy started