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"?
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)') }
(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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With