Skip to content

Instantly share code, notes, and snippets.

@chrisdickinson
Created August 9, 2010 04:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisdickinson/514943 to your computer and use it in GitHub Desktop.
Save chrisdickinson/514943 to your computer and use it in GitHub Desktop.
// modifying the calling function's context
// in javascript to emulate operator overloading OR:
// ...
// now you're thinking with portals
var sys = require('sys');
var Toy = function() {
this.toyList = [];
};
Toy.prototype.valueOf = function() {
arguments.callee.caller.calledList = arguments.callee.caller.calledList === undefined ? [] : arguments.callee.caller.calledList;
this.toyList = this.toyList.concat(arguments.callee.caller.calledList).slice();
arguments.callee.caller.calledList.push(this);
return this;
};
Toy.prototype.toString = function() {
return "<Toy of length "+this.toyList.length+">";
};
var testFn = function(name, fn) {
var t1 = new Toy();
var t2 = new Toy();
sys.puts("Result "+name+":\t" + fn(t1, t2));
sys.puts("\tt1.toyList: "+t1.toyList.length);
sys.puts("\tt2.toyList: "+t2.toyList.length);
};
var test = {'t1 && t2': function(t1, t2) { return t1 && t2; }
,'t1 || t2': function(t1, t2) { return t1 || t2; }
,'t1 & t2': function(t1, t2) { return t1 & t2; }
,'t1 | t2': function(t1, t2) { return t1 | t2; }
,'t1 / t2': function(t1, t2) { return t1 / t2; }
,'t1 << t2': function(t1, t2) { return t1 << t2; }
};
for(var i in test) {
testFn(i, test[i]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment