contents   index   previous   next



instanceof operator

 

The instanceof operator, which also may used as instanceof(), determines if a variable is an instance of a particular object. Since the variable s is created as an instance of the String object in the following code fragment, the second line displays true.

 

var s = new String("abcde");

Screen.writeln(s instanceof String);

 

The display is:

 

true

The second line could also be written as:

 

Screen.writeln(s instanceof(String));

 

The instanceof operator does not work with the class of an object, rather it determines if a variable was constructed from an object. In the example above, the variable s was defined as an instance of String so it is an instance of the String object and is in the class of String. That is, both of the following lines display true:

 

Screen.writeln(s instanceof(String));

Screen.writeln(s._class == "String");

 

The display is:

 

true

true

 

The following code defines a new object and defines the variable ms as an instance of MyString, a user defined object. In this case, the variable ms is an instance of MyString but is in the class of Object.

 

var ms = new MyString("abcde");

Screen.writeln(ms instanceof(MyString));

Screen.writeln(ms._class == "Object");

ms.show();

 

function MyString(string)

{

 

   this.data = string;

   return this;

} // MyString

 

function MyString.prototype.show()

{

   Screen.writeln(this.data);

} // MyString.prototype.show

 

The display is:

 

true

true

abcde

 


typeof operator