Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a function from string which inherits the parent scope

In Javascript, is there a way to create a function from a string (such as through the new Function() constructor) and have it inherit the parent scope? For example:

(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 any way to make whee.testy() also alert "super yay"?

like image 330
antimatter15 Avatar asked Nov 14 '22 12:11

antimatter15


2 Answers

Actually, combining function and eval should 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)') }
like image 184
levik Avatar answered Feb 17 '23 21:02

levik


(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 from any untrusted source. It's just to be used for minifying code.

like image 20
antimatter15 Avatar answered Feb 17 '23 22:02

antimatter15