Skip to content

Instantly share code, notes, and snippets.

@creationix
Created October 1, 2009 20:30
Show Gist options
  • Save creationix/199222 to your computer and use it in GitHub Desktop.
Save creationix/199222 to your computer and use it in GitHub Desktop.
Various implementations of instance_eval for the Javascript Object prototype
include("/utils.js");
// "this" scope is the object, closures work like normal. Basically this is a nowmal "call" use for functions
Object.prototype.instance_eval = function (input) {
// Convert the function to a string so that we can rebind it
if (typeof input === 'function') {
return input.call(this);
}
// Eval using "this" as the "with" scope
return eval("with(this) { " + input + "}");
}
// Change the closure scope of the function by breaking it's semantic binding, this breaks the "this" scope to be null
Object.prototype.instance_eval2 = function (input) {
// Convert the function to a string so that we can rebind it
if (typeof input === 'function') {
input = "(" + input + "())";
}
// Eval using "this" as the "with" scope
return eval("with(this) { " + input + "}");
}
// Break and rebind the local identifiers like above, but also preserve this to be the object too
Object.prototype.instance_eval3 = function (input) {
// Convert the function to a string so that we can rebind it
if (typeof input === 'function') {
input = "(" + input + ").call(this)";
}
// Eval using "this" as the "with" scope
return eval("with(this) { " + input + "}");
}
var first = "Bob";
var last = "Smith";
var custom_scope = {first: "Tim", last: "Caswell"};
var show_name = function () {
return "Object name: " + this.first + " " + this.last + " Closure Name: " + first + " " + last;
}
debug(custom_scope.instance_eval(show_name));
debug(custom_scope.instance_eval2(show_name));
debug(custom_scope.instance_eval3(show_name));
// Output for those who don't yet have nodeJS
// Timothy-Caswells-MacBook-Pro:Desktop tim$ node instance_eval_playground.js
// DEBUG: Object name: Tim Caswell Closure Name: Bob Smith
// DEBUG: Object name: undefined undefined Closure Name: Tim Caswell
// DEBUG: Object name: Tim Caswell Closure Name: Tim Caswell
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment