Created
August 14, 2013 05:28
-
-
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!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
Author
cgiffard
commented
Aug 14, 2013
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment