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" +); +