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!'
Written by Mark Roseboom
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Coffeescript
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#