Skip to content

Instantly share code, notes, and snippets.

@dandean
Created August 5, 2009 21:09
Show Gist options
  • Save dandean/162961 to your computer and use it in GitHub Desktop.
Save dandean/162961 to your computer and use it in GitHub Desktop.
Object.prototype.toString enables really fucking cool equality comparison...
// 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