Created
October 2, 2010 02:52
-
-
Save jasonrhodes/607204 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// D. Crockford's method for adding methods to the prototype object | |
Function.prototype.method = function (name, func) { | |
this.prototype[name] = func; | |
return this; | |
}; | |
// Add is_array function to Array, return true | |
Array.method('is_array', function () { | |
return true; | |
}); | |
// Add is_array function to Object, return false | |
Object.method('is_array', function () { | |
return false; | |
}); | |
var collection_1 = {}; // Object, should return undefined | |
var collection_2 = []; // Array, should return true | |
// Return some intuitive text for testing | |
var test_array = function (collection) { | |
return collection.is_array() ? 'Totally an array.' : 'Definitely not an array, man.'; | |
}; | |
document.writeln(test_array(collection_1)); // Definitely not an array, man. | |
document.writeln(test_array(collection_2)); // Totally an array. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Javascript doesn't come with a native is_array function. The solutions I've seen have seemed unnecessarily complex. I've been wondering why this particular solution wouldn't work?