1
0
Fork 0

Began adding isInstanceOf, starting with prototype chain checks

closure/master
Mike Gerwitz 2010-12-29 21:13:21 -05:00
parent 0103df3e71
commit 96909732db
2 changed files with 48 additions and 0 deletions

View File

@ -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 * Default class implementation
* *

View File

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