Creating a function from a string that inherits the parent scope

Is there a way in Javascript to create a function from a string (for example, through a new Function () constructor) and inherit its parent area? For instance:

(function(){
    function yay(){
    }
    var blah = "super yay"
    yay.prototype.testy = new Function("alert(blah)")
    yay.prototype.hello = function(){alert(blah)}
    whee = new yay();
    whee.hello()
    whee.testy()
})()

Is there a way to make whee.testy () also a "super yay" alert?

+5
source share
6 answers
(function(){
    function yay(){
    }
    var blah = "super yay"
    yay.prototype.testy = eval("(function(){alert(blah)})")//new Function("alert(blah)")
    yay.prototype.hello = function(){alert(blah)}
    whee = new yay();
    whee.hello()
    whee.testy()
})()

This seems to work for me, and none of the eval'd data is the source of any untrusted source. It is simply used to extract code.

+1
source

Actually, the union functionand evalshould do what you want:

// blah exists inside the 'hello' function
yay.prototype.hello = function(){ alert(blah) }
// blah also exists inside the 'testy' function, and
// is therefore accessible to eval().
yay.prototype.testy = function(){ eval('alert(blah)') }
+1
source

, ...

var inputAction = "alert(blah)";
yay.prototype.testy = eval("(function(){ " + inputAction + "; })")

, eval, , .

, , , .

+1

, whee.testy , , new Function("alert(blah)") . blah , , undefined.

:

var blah = "global (window) scope";

(function(){
    function yay(){
    }
    var blah = "closure scope";

    yay.prototype.testy = new Function("alert(blah)");
    yay.prototype.hello = function(){ alert(blah); }
    whee = new yay();
    whee.hello();
    whee.testy();
})();
0

eval?

(function(){
    function yay(){
    }
    var blah = "super yay"
    yay.prototype.testy = new Function(eval("alert(blah)")) // <---------------
    yay.prototype.hello = function(){alert(blah)}
    whee = new yay();
    whee.hello()
    whee.testy()
})()

JS. 1) eval - "", 2) eval .

-1
source

You do not need eval.

You need to combine blah with a string function, but JavaScript will complain about the lack of ";" before concatenation, this happens because blah is just text when you combine it. You must avoid the two "\" "around the blah variable to make it look like a line with text in it.

(function(){
    function yay(){
    }
 var blah = "super yay"

 yay.prototype.testy = new Function("alert(\""+blah+"\")")
 yay.prototype.hello = function(){alert(blah)}
 whee = new yay();
 whee.hello()
 whee.testy()
})()

This will warn “super yay” twice!

-1
source

All Articles