Exercise 11.04
Fixing Scope
specialForms["set"] = function(args, env){
if(args.length !=2 || args[0].type != "word")
throw new SyntaxError("Bad use of set");
var varName = args[0].name;
var value = evaluate(args[1], env);
for (var scope = env; scope; scope=Object.getPrototypeOf(scope)){
if(Object.prototype.hasOwnProperty.call(scope, varName)){
scope[varName]=value;
return value;
}
}
throw new ReferenceError("Setting undefined variable " + varName);
};
run("do(define(x,4),",
" define(setx, fun(val, set(x, val))),",
" setx(50),",
" print(x))");
//->50
run("set(quux, true)");
//->Some kind of ReferenceError
To open the JavaScript console, press F12 or on MAC press COMMAND-OPTION-I.