Created
August 5, 2009 21:09
-
-
Save dandean/162961 to your computer and use it in GitHub Desktop.
Object.prototype.toString enables really fucking cool equality comparison...
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
// Comparison in JavaScript is an interesting thing... | |
var Object1 = { | |
toString: function() { return "!!!"; } | |
}; | |
var Object2 = { | |
toString: function() { return "!!!"; } | |
}; | |
var MySuperRadFunky = Class.create({ | |
initialize: function( ) { | |
// Do some crazy shit here | |
}, | |
toString: function() { return "!!!"; } | |
}); | |
RegExp.prototype.toString = function() { | |
return "!!!"; | |
}; | |
console.log("!!!" == Object1); // true | |
console.log("!!!" === Object1); // false | |
console.log("!!!" == Object2); // true | |
console.log("!!!" === Object2); // false | |
console.log("!!!" == new MySuperRadFunky()); // true | |
console.log("!!!" === new MySuperRadFunky()); // false | |
console.log("!!!" == new RegExp("")); // true | |
console.log("!!!" === new RegExp("")); // false | |
// Example use-case for smart toString methods which enable comparison | |
/** | |
* class ThingCollection | |
**/ | |
var ThingCollection = Class.create({ | |
initialize: function() { this._collection = []; }, | |
add: function(value) { this._collection.push(value); return this; }, | |
/** | |
* Custom toString implementation returns the size of the collection | |
* enabling comparison by number using the == operator, ie: myCollection == 5 | |
**/ | |
toString: function() { return this._collection.length.toString(); } | |
}); | |
var myCollection = new ThingCollection(); | |
console.log(5 == myCollection); // false | |
myCollection.add(null).add("something"); | |
console.log(5 == myCollection); // false | |
myCollection.add("rad").add("awesome").add("stuff"); | |
console.log(5 == myCollection); // true!!! | |
// myCollection is getting converted to "5" automatically via the ThingCollection.toString method | |
// And since myCollection is converted to the String "5", 5 is also converted to a string | |
// before comparison. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment