The instanceof operator can be used to determine whether the prototype attribute of a constructor exists on another prototype chain to detect the object.
Example 1: Common usage
A instanceof B: Detect whether B.prototype exists on the prototype chain of parameter A.
function Ben() {}var ben = new Ben();console.log(ben instanceof Ben);//trueExample 2: In inheritance, determine whether an instance belongs to its parent class
function Ben_parent() {}function Ben_son() {}Ben_son.prototype = new Ben_parent();//Prototype inheritance var ben_son = new Ben_son();console.log(ben_son instanceof Ben_son);//trueconsole.log(ben_son instanceof Ben_parent);//trueExample 3: Indicates that both String objects and Date objects belong to Object types
The following code uses instanceof to prove that String and Date objects also belong to the Object type.
var simpleStr = "This is a simple string"; var myString = new String();var newStr = new String("String created with constructor");var myDate = new Date();var myObj = {};simpleStr instanceof String; // returns false, check the prototype chain and find undefinedmyString instanceof String; // returns truenewStr instanceof String; // returns truemyString instanceof Object; // returns truemyObj instanceof Object; // returns true, despite an undefined prototype({}) instanceof Object; // returns true, same as above myString instanceof Date; // returns false instanceof Date; // returns truemyDate instanceof Object; // returns truemyDate instanceof String; // returns falseExample 4: Demonstrate mycar belongs to the Car type and also belongs to the Object type
The following code creates a type Car, and an object instance of the type mycar. The instanceof operator indicates that this mycar object belongs to both the Car type and the Object type.
function Car(make, model, year) { this.make = make; this.model = model; this.year = year;}var mycar = new Car("Honda", "Accord", 1998);var a = mycar instanceof Car; // Return truevar b = mycar instanceof Object; // Return true