Accessing variables trapped by closure

A simple eval inside the closure scope can still access all the variables:

function Auth(username)
{
  var password = "trustno1";
  this.getUsername = function() { return username }
  this.eval = function(name) { return eval(name) }
}

auth = new Auth("Mulder")
auth.eval("username") // will print "Mulder"
auth.eval("password") // will print "trustno1"

But you cannot directly overwrite a method, which is accessing closure scope (like getUsername()), you need a simple eval-trick also:

auth.eval("this.getUsername = " + function() {
  return "Hacked " + username;
}.toSource());
auth.getUsername(); // will print "Hacked Mulder"

Leave a Comment