instanceof

Summary

For internal types, instanceof determines if an object is compatible with a specified type or one of its ancestors. For external types, instanceof determines if one object is in the prototype chain of another.

Syntax

object instanceof type

Parameters

object
The object to test.
type
The type or external JavaScript object to test for.

Description

For JS++ types, the instanceof operator will check if an object is compatible with a specified type or one of its ancestors.

For example, if a variable named d was instantiated based on a class named Dog, the variable d will be an "instance of" the Dog class, and the instanceof operator will return true. If the Dog class inherits from an Animal class, d will still be an "instance of" the Animal class, and the instanceof operator will still return true. However, if there is a class Cat with no inheritance relationship to Dog, instanceof will return false.

For JavaScript code, represented with the external type, the instanceof operator returns true if the first object is in the prototype chain of the second object (the object to test for); otherwise, it returns false.

Examples

Basic Usage
1
2
3
4
class Dog {}
 
Dog dog = new Dog();
bool isType = dog instanceof Dog; // true
'instanceof' with Inheritance
1
2
3
4
5
6
class Animal {}
class Dog : Animal {}
 
Dog dog = new Dog();
bool isType = dog instanceof Dog;         // true
bool isSuperType = dog instanceof Animal; // true
'instanceof' with incompatible type
1
2
3
4
5
6
class Animal {}
class Dog : Animal {}
class Cat : Animal {}
 
Dog dog = new Dog();
bool isType = dog instanceof Cat; // false
'instanceof' with Interfaces
1
2
3
4
5
6
class IAnimal {}
class Animal : IAnimal {}
class Dog : Animal {}
 
Dog dog = new Dog();
bool isType = dog instanceof IAnimal; // true
Using 'instanceof' with JavaScript Prototypical Inheritance
1
2
3
4
5
6
7
function Gift(){}
function Meal(){}
function Dinner(){}
Dinner.prototype = new Meal();
 
var pasta = new Dinner();
bool pd = pasta instanceof Meal; // true

See Also

Share

HTML | BBCode | Direct Link