Skip to content

Instantly share code, notes, and snippets.

@cgiffard
Created August 14, 2013 05:28
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 cgiffard/6228242 to your computer and use it in GitHub Desktop.
Save cgiffard/6228242 to your computer and use it in GitHub Desktop.
Guess what. Overloading the JS += operator is possible, if a little contrived and probably unusable!
var assert = require("assert");
var store = {};
function resolve(item) {
return store[item];
}
var FancyObject = function() {
var arrayProperty = [];
Object.defineProperty(
this,
"arrayProperty",
{
"set": function(newItem) {
arrayProperty.push(resolve(newItem));
},
"get": function() {
var prop = arrayProperty.slice(0);
prop.valueOf = function() {
return 0;
}
return prop;
}
}
);
};
FancyObject.prototype = {};
FancyObject.prototype.valueOf = function() {
var key = Math.random();
store[key] = this;
return key;
}
var assignTo = new FancyObject(),
assignee = new FancyObject();
assignee.easyIdentifier = 1234567;
console.log(
"Items in the object we're assigning to? %d",
assignTo.arrayProperty.length);
assignTo.arrayProperty += assignee;
console.log(
"Items in the object we're assigning to after increment op: %d",
assignTo.arrayProperty.length);
assert(assignTo.arrayProperty[0].easyIdentifier === 1234567);
@cgiffard
Copy link
Author

cgiffard@crunktown.local overloading
➭  node overloading.js 
Items in the object we're assigning to? 0
Items in the object we're assigning to after increment op: 1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment