Call function on object literal, represented by string - JavaScript -


i using history.js. in stateobj of pushstate function, want add reference function (car.init(), or boat.init(). in c++, believe use function pointer.

then on window.onpopstate, want reference function , call it. can read string (car.init(), how can call function? don't want use eval.

you shouldn't, if want invoke function based on global dotted-path name, accomplished this:

function callfunction(name, var_args) {    // break string individual property/method names    var parts = name.split('.');      // start reference global object    var target = window;    var previoustarget = null;      (var = 0; < parts.length; i++) {      // keep copy of previous reference use `this` value      previoustarget = target;        // change reference next named property      target = target[parts[i]];    }      // grab remaining arguments    var args = array.prototype.slice.call(arguments, 1);      // call target function, previoustarget subject, using args    return target.apply(previoustarget, args);  }    // in top-level/global scope. won't work local definition.  var myapp = {    currentuser: {      name: 'joe',      displayname: function(greeting) {        alert(greeting + " ," + this.name + "!");      }    },    openbar: function() {      alert("the foo bar open business!");    }  };    var functionname = 'myapp.currentuser.displayname';  callfunction(functionname, "hello");

this safer using eval (good call on avoiding it), still pretty wacky , difficult javascript interpreters optimize. instead, recommended approach use reference (pointer) function. similar you'd in c++. if function doesn't use this (i.e. if it's static function, not method), can take reference function directly.

var open = myapp.openbar; open(); 

if have this value, you'll need use .bind() method preserve association object it's attached to.

var display = myapp.currentuser.displayname.bind(myapp.currentuser); display("greetings"); 

if pass additional arguments .bind(), can specify leading arguments used call function.

var displayhello = myapp.currentuser.displayname.bind(myapp.currentuser, "hello"); displayhello(); 

Comments

Popular posts from this blog

java - Suppress Jboss version details from HTTP error response -

gridview - Yii2 DataPorivider $totalSum for a column -

Sass watch command compiles .scss files before full sftp upload -