Jennifer Massey
Jennifer Massey

Reputation: 173

What's the point of returning via the Function() Constructor

The JQuery ParseJSON code has the following structure:

function( data ) {
        // regular expression manipulations involving data
        return (new Function( "return " + data ))();
}

and I'm wondering why not use return data instead? Thank you!

Upvotes: 2

Views: 25

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388406

data is a string, so if you say return data, it will just return the same string what was passed to it...

function( data ) {
        // regular expression manipulations involving data
        return (new Function( "return " + data ))();
}

In the above snippet we are creating a new function which returns an object like if data was '{"test":"somevalue"}' then you have "return" + '{"test":"somevalue"}' so the concatenated string is "return {"test":"somevalue"}"(new Function('return {"test":"somevalue"}')()) which is like returning an object.

Upvotes: 2

Related Questions