Export (0) Print
Expand All

instanceof Operator 

Returns a Boolean value that indicates whether or not an object is an instance of a particular class or constructed function.


object instanceof class

object

Required. Any object expression.

class

Required. Any object class or constructed function.

The instanceof operator returns true if object is an instance of class or constructed function. It returns false if object is not an instance of the specified class or function, or if object is null.

The JScript Object is special. An object is only considered an instance of Object if and only if the object was constructed with the Object constructor.

The following example illustrates a use of the instanceof operator to check the type of a variable.

// This program uses System.DateTime, which must be imported.
import System

function isDate(ob) : String {
   if (ob instanceof Date)
      return "It's a JScript Date"
   if (ob instanceof DateTime)
      return "It's a .NET Framework Date"
   return "It's not a date"
}

var d1 : DateTime = DateTime.Now
var d2 : Date = new Date
print(isDate(d1))
print(isDate(d2))

The output of this code is:

It's a .NET Date
It's a JScript Date

The following example illustrates a use of the instanceof operator to check instances of a constructed function.

function square(x : int) : int {
   return x*x
}

function bracket(s : String) : String{
   return("[" + s + "]");
}

var f = new square
print(f instanceof square)
print(f instanceof bracket)

The output of this code is:

true
false

The following example illustrates how the instanceof operator checks if objects are instances of Object.

class CDerived extends Object {
   var x : double;
}

var f : CDerived = new CDerived;
var ob : Object = f;
print(ob instanceof Object);

ob = new Object;
print(ob instanceof Object);

The output of this code is:

false
true

Community Additions

ADD
Show:
© 2014 Microsoft