Last Updated: July 16, 2021
·
2.282K
· mroseboom

How to trick instanceof

instanceof searches for the constructor.prototype in the given object's prototype chain. So by understanding prototypal inheritance, we can manipulate that comparison.

n = new Number()
n instanceof Number # true
n.__proto__ = String.prototype
n instanceof Number # false
n.instanceof String # true

This becomes useful when writing tests for an instanceof check of a complex object that you don't want to recreate for the test. An example method and Jasmine spec for it are below:

checkObject (input) ->
  if input instanceof ObjectA
    'its ObjectA!'
  else if input instanceof ObjectB
    'its ObjectB!'


 describe 'checkObject', ->    
    it 'returns correctly based on object passed' , ->
      o = {}.__proto__ = ObjectA.prototype
      expect(checkObject o).toEqual 'its ObjectA!'

      o = {}.__proto__ = ObjectB.prototype
      expect(checkObject o).toEqual 'its ObjectB!'