Skip to content

Instantly share code, notes, and snippets.

@gryzzly
Created January 21, 2012 15:18
Show Gist options
  • Save gryzzly/1653043 to your computer and use it in GitHub Desktop.
Save gryzzly/1653043 to your computer and use it in GitHub Desktop.
instanceof vs Object.prototype.toString
!function () {
// helper to set prototype chain up
var Constructor = function () {};
Constructor.prototype = Array.prototype;
var NotRealArray = function () {};
// inherit from Array
NotRealArray.prototype = new Constructor;
// create an instance
var notRealArray = new NotRealArray;
// instanceof
console.log( notRealArray instanceof Array ); // prints true, since instanceof just looks for "constructor" property in prototype chain
// Object.prototype.toString
console.log( ({}).toString.call( notRealArray ).indexOf('Array') !== -1 ); // prints false, ({}).toString.call() returns "[object Object]" here
}();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment