Has instance symbol which is used to determine if a constructor object recognizes an object as its instance.
var HasInstanceSymbol = require( '@stdlib/symbol/has-instance' );Has instance symbol which is used to determine if a constructor object recognizes an object as its instance.
var s = typeof HasInstanceSymbol;
// e.g., returns 'symbol'-
The symbol is only supported in environments which support symbols. In non-supporting environments, the value is
null. -
The
instanceofoperator uses the following algorithm to determine the return value ofobject instanceof constructor:- If
constructorhas a[HasInstanceSymbol]()method, theinstanceofoperator calls the method withobjectas the first argument and returns the result (coerced to a boolean). Ifconstructoris not an object or ifconstructor[HasInstanceSymbol]is neithernull,undefined, nor a function, theinstanceofoperator raises an exception. - Otherwise, if
constructordoes not have a[HasInstanceSymbol]()method (i.e.,constructor[HasInstanceSymbol]isnullorundefined), theinstanceofoperator determines the result using the same algorithm asFunction.prototype[HasInstanceSymbol](). Ifconstructoris not a function, theinstanceofoperator raises an exception.
- If
var isArray = require( '@stdlib/assert/is-array' );
var instanceOf = require( '@stdlib/assert/instance-of' );
var defineProperty = require( '@stdlib/utils/define-property' );
var HasInstanceSymbol = require( '@stdlib/symbol/has-instance' );
function ArrayLike() {
return {
'length': 3,
'0': 4,
'1': 5,
'2': 6
};
}
function hasInstance( instance ) {
return isArray( instance );
}
var x = [ 1, 2, 3 ];
defineProperty( ArrayLike, HasInstanceSymbol, {
'configurable': true,
'value': null
});
console.log( instanceOf( x, ArrayLike ) );
defineProperty( ArrayLike, HasInstanceSymbol, {
'configurable': true,
'value': hasInstance
});
console.log( instanceOf( x, ArrayLike ) );