From 96909732db7c767f0172e20efb46305c0d535095 Mon Sep 17 00:00:00 2001 From: Mike Gerwitz Date: Wed, 29 Dec 2010 21:13:21 -0500 Subject: [PATCH] Began adding isInstanceOf, starting with prototype chain checks --- lib/class.js | 30 ++++++++++++++++++++++++++++++ test/test-class.js | 18 ++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/lib/class.js b/lib/class.js index e660c7d..7963020 100644 --- a/lib/class.js +++ b/lib/class.js @@ -76,6 +76,36 @@ exports.isClassInstance = function( obj ) }; +/** + * Determines if the class is an instance of the given type + * + * The given type can be a class, interface, trait or any other type of object. + * It may be used in place of the 'instanceof' operator and contains additional + * enhancements that the operator is unable to provide due to prototypal + * restrictions. + * + * @param {Object} type expected type + * @param {Object} instance instance to check + * + * @return {boolean} true if instance is an instance of type, otherwise false + */ +exports.isInstanceOf = function( type, instance ) +{ + try + { + // check prototype chain (with throw an error if type is not a + // constructor (function) + if ( instance instanceof type ) + { + return true; + } + } + catch ( e ) {} + + return false; +}; + + /** * Default class implementation * diff --git a/test/test-class.js b/test/test-class.js index c7ec50a..6d8c62b 100644 --- a/test/test-class.js +++ b/test/test-class.js @@ -91,3 +91,21 @@ if ( Object.isFrozen ) ); } + +// +// isInstanceOf +assert.ok( + Class.isInstanceOf( Foo, new Foo() ), + "Class instance is recognized by Class.isInstanceOf()" +); + +assert.ok( + !( Class.isInstanceOf( Foo, Foo ) ), + "Class is not an instance of itself when uninstantiated" +); + +assert.ok( + !( Class.isInstanceOf( new Foo(), Foo ) ), + "Class is not an instance of its instance" +); +