Last Updated: July 16, 2021
·
2.925K
· 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!'

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside