How to evaluate a variable to access its runtime value in JavaScript?
Ok, I don't know how to actually ask this question without showing it. (Also explains why I can't figure out how to search for it on Google.)
Given the following like of code:
dijit.byId('leftNavigationPane').onLoad = function(){setSecondaryNav(url.secondaryNavId);};
I want the variable url.secondaryNavId
to be evaluated开发者_运维知识库, so what I really want is it to be treated something like this:
dijit.byId('leftNavigationPane').onLoad = function(){ setSecondaryNav('item1'); };
I am sure there is probably a better way to do this, so feel free to suggest something.
Don't use eval
!
You can use a self-invoking function and closures as follows:
dijit.byId('leftNavigationPane').onLoad = function(id){
return function(){ setSecondaryNav(id); };
}(url.secondaryNavId);
This will execute the outer anonymous function immediately (at runtime), passing the url.secondaryNavId
parameter, which will then create a closure that the inner anonymous function will use (so id
will always contain the assignment-time value of the url.secondaryNavId
property).
There is the JavaScript eval() function.
精彩评论