I would like to do the following in JavaScript:
var myObject.name = myString;
function newFunction(){myObject.name}
Is it possible to use a string as the contents of a function? How would you convert it to be usable?
Ok, I get what you're trying to do. You can do it like this:
var newFunction = new Function(myObject.name);
This means if myObject.name equals "alert('it works')", when you call newFunction() you will be alerted. (new Function(code) is an alternative to eval, specifically for what you're doing.)
But this is considered very bad practice in JavaScript (and in programming in general), as code that can alter itself can quickly become unmanageable, and there's usually a better way to do things. Unless you show us what it is you're doing, I can't say what that better way is.
eval(). It's a bit cleaner syntactically. +1.I believe you want myString to hold code, right ?
You can execute that code by using the eval()MDN docs method.
function newFunction(){ eval(myObject.name); }
Warning !
be sure to read the Don't use eval! section though ..
JavaScript has the eval() function but that's generally not a function you want to be using...
You'd then write:
var myObject.name = myString;
function newFunction() {
eval(myObject.name);
}
However, this is generally a dangerous and bad idea - on a higher level, what are you trying to do?
return myObject.nameto get the string back out of the function, but unless that's what you're after, we need to know more about what your goal is.myString = "return x;"-in which case he could useeval()myObject.nameas javascript and execute it? if so you could use evalvar myObject.name = "x=1,y=1" "function(){myObject.name; var myArray = []; myArray = myObject.name; return myArray}