The typeof operator is often used to determine the typeof variables in JavaScript, but one drawback with typeof is that when determining a reference type stores a value, it returns “object” no matter what typeof object it refers to. ECMAScript introduces another Java operator, Instanceof, to solve this problem. The instanceof operator is similar to the typeof operator and is used to identify the typeof object being processed. Unlike the Typeof method, the Instanceof method requires the developer to explicitly identify the object as a particular type.

1. Usage of the instanceof operator

var strObj = new String("go go go, don't stop!!!" ); console.log(strObj instanceof String); // trueCopy the code

This code determines whether the strObj variable is an instance of String. StrObj is an instance of String and therefore “true”. Although not as flexible as typeof methods, instanceof methods can be useful in cases where typeof methods return “object.”

Function foo (){} var foo = new foo (); console.log(foo instanceof Foo) // trueCopy the code

2. Instanceof is used in inheritance relationships

Function Aoo(){} function foo (){} foo. Prototype = new Aoo(); Var foo = new foo (); console.log(foo instanceof Foo)//true console.log(foo instanceof Aoo)//trueCopy the code

Foo is an instance of the constructor foo, because the constructor foo stereotype inherits the constructor Aoo and therefore returns true. In this code, the parent class in a hierarchy is determined. In a hierarchy, the instanceof operator is also applicable.

3. Instanceof operator code

Function instance_of(L, R) {var O = r.protoType; // take the display prototype of R L = l.__proto__; While (true) {if (L === null) return false; If (O === L) // return true when O is exactly L; L = L.__proto__; }}Copy the code

4. Complex use of instanceof

 console.log(Object instanceof Object); // true
 console.log(Function instanceof Function); // true
 console.log(Number instanceof Number); // false
 console.log(String instanceof String); // false
 console.log(Function instanceof Object); // true
 console.log(Foo instanceof Function); // true
 console.log(Foo instanceof Foo); // false
Copy the code

To verify the above conclusion, we need to first understand JavaScript inheritance. The prototype inheritance mechanism is shown below

 1).Object instanceof Object

ObjectL = Object, ObjectR = Object; Prototype L = ObjectL.__proto__ = Function. Prototype Prototype = Function. Prototype.__proto__ = object. prototype // second check O == L // return trueCopy the code

2).Function instanceof Function

FunctionL = Function, FunctionR = Function; Prototype L = FunctionL.__proto__ = function. prototype / / return trueCopy the code

3). Foo instanceof Foo

// FooL = Foo, FooR = Foo; Prototype L = FooL.__proto__ = Function. Prototype L = FooL. Prototype = Function. Prototype.__proto__ = Object. Prototype. __proto__ = null // returns false for the third timeCopy the code