dfred
dfred

Reputation: 443

Use name of object to run a function

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?

Upvotes: 0

Views: 70

Answers (4)

Nathan
Nathan

Reputation: 11149

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.

Upvotes: 2

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195992

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 ..

Upvotes: 0

Kristian Glass
Kristian Glass

Reputation: 38510

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?

Upvotes: 0

ThinkingStiff
ThinkingStiff

Reputation: 65341

You can use eval() to do this, assuming myObject.name contains valid Javascript:

function newFunction(){ eval( myObject.name ); };

Upvotes: 1

Related Questions