The instanceof operator can be used to determine whether a constructor's prototype property exists on another prototype chain to detect an object.
Example one: Universal usage
A instanceof B: detects whether the B.prototype exists on the prototype chain of parameter A.
Function Ben () {
}
var ben = new Ben ();
Console.log (Ben instanceof Ben);//true
Instance two: Determines whether an instance belongs to its parent class in inheritance
function Ben_parent () {}
function Ben_son () {}
Ben_son.prototype = new Ben_parent ();/prototype Inherits
var Ben_son = New Ben_son ();
Console.log (Ben_son instanceof Ben_son);//true console.log (Ben_son instanceof
); ben_parent
Example three: Indicates that a string object and a Date object belong to type Object
The following code uses instanceof to prove that a string and a Date object also belong to type object.
var simplestr = "This was 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 that the prototype chain will find undefined
myString instanceof string;//returns True
newstr string; Returns True
myString instanceof object;//returns True
myobj instanceof object; Returns true, despite an undefined prototype
({}) instanceof Object; Returns True, Ibid.
myString instanceof Date; Returns false
mydate instanceof Date; Returns True
mydate instanceof Object; Returns True
mydate instanceof String; Returns false
Example four: Demonstrates that Mycar belongs to the type of car and is of type Object
The following code creates a type car and an object instance of that type, Mycar. The instanceof operator indicates that the 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; Returns True
var b = mycar instanceof Object;//return True