Prototype debugging

18 December 2010

By adding a toString method to your prototypes you can help yourself with debugging the always handy [object] string. This is because functions and objects inherit from Object, which has a toString method.

var myPrototype = {
  toString : function () {
    return '[object myPrototype]';
  }
};

Other Uses

This also comes in handy when determining if an object is an array.

var myArray = [];
console.warn(Object.prototype.toString.call(myArray));

Which will output [object Array]. So we can run this boolean test:

Object.prototype.toString.call(myArray) === '[object Array]';

Super handy, but sometimes an Array has a property isArray (ES5), which is an inbuilt browser property so it will be faster than the toString method. So we can we write a high level function to decide if an object is an Array.

var isArray = Array.prototype.isArray 
        ? function (arr) {
            return arr.isArray;
          }
        : function (arr) {
            return Object.prototype.toString.call(arr) === '[object Array]';
          };

Matt Sain

Ramblings of a developer, designer and child subscribe

This blog is a public GitHub repository. If you find an error I will not be surprised... but if you fork and edit the blog and send me a pull request you'd be pretty awesome in my book.

Featured Repos