Using a javascript Object attribute's value as a function name -


i have following javascript code

function myfunc () {      var add = function () {         return "hello add";     };      var div = function () {          return "hello div";     };      var funccall =  function (obj) {          if (!obj) {             throw new error("no objects passed");         }       return obj.fname();       };    return {     func: function (obj) {       funccall(obj);     }   };  }  var lol = new myfunc(); 

when lol.func({fname: add}); passed should invoke function private function add or when lol.func({fname: div}); passed should invoke private div function. have being tried not work. how can achieve this.

demo

in case it's better store inner function in object can access variable name. if define function "map"

var methods = {     add: add,     div: div }; 

you able call methods[obj.fname]();.

full code:

function myfunc() {      var add = function () {         return "hello add";     };      var div = function () {         return "hello div";     };      var methods = {         add: add,         div: div     };      var funccall = function (obj) {          if (!obj) {             throw new error("no objects passed");         }          return methods[obj.fname]();     };      return {         func: function (obj) {             return funccall(obj);         }     };  }  var lol = new myfunc(); console.log( lol.func({fname: 'add'}) ); 

Comments

Popular posts from this blog

Fail to load namespace Spring Security http://www.springframework.org/security/tags -

sql - MySQL query optimization using coalesce -

unity3d - Unity local avoidance in user created world -