flyandi
flyandi

Reputation: 1939

Limitations of JavaScript's Function constructor

Here is something weird, and I don't know how to overcome it.

Basically, I have this string here:

var s = 'var Bla = {variable: true, get: function() { return this.variable;}}; return Bla;'

and using the Function constructor to parse this construct.

var fn = new Function(s);

It works great, except that the inside function 'get' is no longer there .. like it didn't got parsed?!

fn().variable  -> is there and returns "true".
fn().get  -> is undefined, not existing.

Any ideas?

PS: I edited my original question to indicate what's really missing.

Upvotes: 0

Views: 152

Answers (2)

James Thorpe
James Thorpe

Reputation: 32212

The code you've posted is the equivalent of this:

var fn = function() {
    var Bla = {
        variable: true, 
        get: function() { 
            return this.variable;
        }
    };
    return Bla;
}

So you can't directly use fn.variable or fn.get - instead you need to call that function:

var x = fn();
alert(x.get()); //alerts true
x.variable = 1;
alert(x.get()); //alerts 1

Bla is just a local variable within the function, and doesn't get returned from it. The code could easily just have been:

var fn = function() {
    return {
        variable: true, 
        get: function() { 
            return this.variable;
        }
    };
}

And you'd get the same effect. After calling the function, the object returned from it is what contains variable and get:

example object

Upvotes: 4

Will Hitchcock
Will Hitchcock

Reputation: 9

Your example works fine.

I tried it and issuing:

fn().get()

returns true as you'd expect.

Upvotes: 0

Related Questions