Began adding isInstanceOf, starting with prototype chain checks
parent
0103df3e71
commit
96909732db
30
lib/class.js
30
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
|
* Default class implementation
|
||||||
*
|
*
|
||||||
|
|
|
@ -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"
|
||||||
|
);
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue