Skip to content

Instantly share code, notes, and snippets.

@jasonrhodes
Created October 2, 2010 02:52
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 jasonrhodes/607204 to your computer and use it in GitHub Desktop.
Save jasonrhodes/607204 to your computer and use it in GitHub Desktop.
// 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.
@jasonrhodes
Copy link
Author

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?

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