The main content of this article comes from DeveloperWorks ...
In JavaScript, judging the type of a variable with the typeof operator, a problem occurs when you store a value with a reference type using the TypeOf operator, which returns "object" regardless of what type of object is referenced. ECMAScript introduced another Java operator, instanceof, to solve this problem.
The instanceof operator is similar to the typeof operator to identify the type of object being processed. Unlike the TypeOf method, the Instanceof method requires the developer to explicitly confirm that the object is of a particular type.
instanceof Example
var ostringobject = new String ("Hello World"); Console.log (Ostringobject instanceof String); Output "true"
This code asks "is the variable ostringobject an instance of a String object?" "Ostringobject is indeed an instance of a String object, so the result is" true ". Although not as flexible as the TypeOf method, the Instanceof method is useful in cases where the TypeOf method returns "Object".
instanceof General Usage
Generally speaking, using instanceof is to determine whether an instance is of a certain type. For example:
Determine if Foo is an instance of the Foo class, function foo () {} var foo = new Foo (); Console.log (foo instanceof foo)//true
The heavier point is that instanceof can be used in an inheritance relationship to determine whether an instance belongs to its parent type. For example:
//Determine if Foo is an instance of the Foo class and whether it is an instance of its parent type function Aoo () {} function foo () {} Foo.prototype = new Aoo ();//javascript Prototype inherits var foo = new Foo (); Console.log (foo instanceof foo)//true console.log (foo instanceof Aoo)//true
The above code determines the parent class in a hierarchy of inheritance relationships, and the instanceof operator is also applicable in multi-tier inheritance relationships.
Looking at the above code example, is not to think that the instanceof operator is very simple, the following is a bit of complex usage.
instanceof Complex usage
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
Did you see the code above? Why does Object and Function instanceof themselves equal to true, while other classes instanceof themselves not equal to true? How to explain? To fundamentally understand the mysteries of instanceof, we need to start with two aspects:
1, how the operator is defined in the language specification.
2,javascript the prototype inheritance mechanism.
detailed anatomy of the definition of the instanceof operator in ECMAScript-262 edition 3
11.8.6 the instanceof operator the production relationalexpression:relationalexpression instanceof Shiftexpression is E Valuated as follows:1. Evaluate relationalexpression. 2. Call GetValue (Result (1)).//Calls the GetValue method to get the value of result (1), set to result (2) 3. Evaluate shiftexpression. 4. Call GetValue (Result (3)).//Similarly, this is set to result (4) 5. If result (4) is not a object, throw a TypeError exception.//if result (4) isn't an object, Throws an exception/* if Result (4) does not have a [[Hasinstance]] method, throws an exception. all [[...]] methods or properties in the specification are internal and cannot be used directly in JavaScript. And the specification shows that only the Function object implements the [[Hasinstance]] method. So here's a simple idea: if Result (4) is not a Function object, throw an exception */6. If Result (4) does not has a [[Hasinstance]] method, throw a TypeError exception. Equivalent to this invocation: Result (4). [[Hasinstance]] (Result (2)) 7. Call the [[[Hasinstance]] method of result (4) with parameter result (2). 8. Return Result (7). Related Hasinstance method Definition 15.3.5.3 [[hasinstance]] (V) Assume F is a Function object.// Here F is the result (4) above, and V is the result (2) when the [[Hasinstance]] method of F was called with value V, and the following steps is Taken:1. If V is not a object, return false.//if V is not object, returns false 2 directly. Call the [[get]] method of F with property name "Prototype".//using [[get]] methods F's Prototype Property 3. Let O is Result (2).//o = F.[[get]] ("prototype") 4. If O is not an object, throw a TypeError exception. 5. Let V is the value of the [[Prototype]] property of v.//v = V.[[prototype]] 6. If V is null, return FALSE. Here is the key, if O and V refer to the same object, then return true; otherwise, go to step 8 to return to step 5 to continue the Loop 7. If O and V refer to the same object or if they refer to objects joined to each other (section 13.1.2), return True. 8. Go to step 5.
The specification definition above is obscure and looks more complex, involving many concepts, but translating this specification into JavaScript code is simple, as follows:
function instance_of (l, R) {//l represents the left expression, R represents the right expression var O = r.prototype;//The display prototype of R = l.__proto__;//takes L as an implicit prototype while (true) { if (L = = = null) return false; if (o = = = L)//Here Focus: When O is strictly equal to L, returns true to return True ; L = l.__proto__; } }
JS prototype inheritance mechanism
Since this article focuses on parsing the JavaScript instanceof operator, the prototype inheritance mechanism for JavaScript is no longer explained in detail, and the following reference is from HTTP://WWW.MOLLYPAGES.ORG/MISC/JS.MP A picture that describes in detail the display of various JavaScript objects and the implicit prototype chain structure.
This article deals with the display of prototypes and implicit prototypes, so let's take a brief look at these two concepts below. In the JavaScript prototype inheritance structure, the specification uses [[Prototype]] to represent an implicit prototype of an object, which is represented in JavaScript in __proto__, and can be accessed in Firefox and Chrome, but I E can't. All JavaScript objects have the __proto__ property, but only object.prototype.__proto__ is null if this property is not modified under Firefox or Chrome. This property points to its prototype object. As for the display of the prototype, in JavaScript with the prototype attribute, this is the basic knowledge of JavaScript prototype inheritance, is not described here.
JS prototype chain :
with the instanceof operator above JavaScript code and prototype inheritance diagrams, and then to understand the instanceof operator will be a breeze. The following is a detailed explanation of the three examples of Object instanceof object,function instanceof Function and foo instanceof foo, which other sample readers can deduce themselves.
object instanceof Object
//for ease of expression, First distinguish between the left and right expressions Objectl = object, Objectr = object; The following progressive deduction according to specification o = Objectr.prototype = Object.prototype L = objectl.__proto__ = function.prototype//First judgment o! = L//Loop Find if L also have __proto__ L = function.prototype.__proto__ = object.prototype//second judgment O = = L//return true
function instanceof Function
// For ease of expression, first distinguish between the left and right expressions
Functionl = function, Functionr = function; The following progressive deduction according to specification o = Functionr.prototype = Function.prototype L = functionl.__proto__ = function.prototype//First judgment o = = L Returns true
foo instanceof Foo
// For ease of expression, first distinguish between the left and right expressions
fool = foo, foor = foo; The following progressive deduction according to specification o = Foor.prototype = foo.prototype L = fool.__proto__ = Function.prototype //First judgment o! = L //Loop Find again if L still have __proto__ l = function.prototype.__proto__ = Object.prototype //second judgment O! = L //re-loop to find if L still have __p roto__ L = object.prototype.__proto__ = null //Third judgment L = = NULL //return False
In JavaScript, there is no concept of multiple inheritance, just like Java. However, when declaring a class using declare in Dojo, it is allowed to inherit from more than one class. The following is an example of Dojo 1.6.1.
Multiple inheritance in Dojo
Dojo.declare ("Boo", null,{}); Dojo.declare ("Foo", [aoo,boo],{}); var foo = new Foo (); Console.log (foo instanceof Aoo);//true console.log (foo instanceof Boo);//false Console.log (Foo.isinstanceof (Aoo));// True Console.log (foo.isinstanceof (Boo));//true
Analysis of Js Operation appended instanceof