JavaScript instanceof operator in-depth anatomy

Source: Internet
Author: User
Tags throw exception

Introduction to the instanceof operator

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. For example:

Listing 1. 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".

General usage of the instanceof operator

Generally speaking, using instanceof is to determine whether an instance is of a certain type. For example:

Listing 2. instanceof General Usage
Determine if Foo is an instance of the Foo class, function foo () {} var foo = new Foo (); Console.log (foo instanceof foo)//true

In addition, 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:

Listing 3. The usage of instanceof in the relationship of inheritance
Determines 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.

Do you really know the instanceof operator?

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.

Listing 4. 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, you need to start with two aspects: 1, how the operator is defined in the language specification. 2,javascript the prototype inheritance mechanism.

Back to top of page

Detailed anatomy of the definition of the instanceof operator in ECMAScript-262 edition 3

The instanceof operator in the language specification pair is defined as follows:

Listing 5. instanceof operator definition in specification
 11.8.6 the instanceof operator  the production relationalexpression:   RelationalExpression instanceof ShiftExpression is evaluated as  Follows:  1. evaluate relationalexpression.  2. call getvalue (Result (1 ) .//  call  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 an object, throw a TypeError  exception.//  if  result (4)   not  object,                                                                   //throws an exception  /*  if  result (4)   No  [[HasInstance]]  method, throws an exception. All  [[in the specification ...]   Methods or properties are internal and cannot be used directly in  JavaScript . And the specification shows that only the  Function  object realizes the  [[HasInstance]]  method. So here can be simply understood as: if  result (4)   Not  Function  object, throw exception  */  6. if result (4)  does not have a [[hasinstance]] method,    throw a  TypeError exception.  //  is 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 above the  result (4),v  is &nbsP Result (2)   When the [[HasInstance]] method of F is called  With value v,  the following steps are taken:  1. if  V is not an object, return false.//  if  V  is not  object, Direct return  false  2. Call the [[Get]] method of F with  property name  "prototype" .//  using  [[Get]]  method to take                                                                      // F   prototype  Properties  3. let o be result (2) .//o = f.[[get]] ("pRototype ")   4. if o is not an object, throw a typeerror  exception.  5. let v be 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, to  Step 8  return  Step 5  continue 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:

Listing 6. JavaScript instanceof Operator Code
function instance_of (l, R) {//l represents the left expression, R represents the right expression var O = r.prototype;//R's display prototype L = l.__proto__;//takes L's implicit prototype while (tr     UE) {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__; }  }

Back to top of page

JavaScript 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.

Figure 1. JavaScript prototype chain

Back to top of page

Explaining instanceof complex usage

With the JavaScript code and prototype inheritance diagram of the instanceof operator above, it is easy to understand the instanceof operator. 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.

Listing 7. Object Instanceof Object
To facilitate the presentation, 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
Listing 8. function instanceof function
To facilitate the presentation, 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
Listing 9. Foo instanceof foo
To facilitate the presentation, first distinguish between the left and right expressions fool = foo, foor = foo; The following progressive deduction according to specifications o = Foor.prototype = Foo.prototype L = fool.__proto__ = function.prototype//First judgment o! = L//loop again to find if l and __proto__ L = function.prototype.__proto__ = object.prototype//second judgment O! = L//loop again to find if l have __proto__ l = Object . prototype.__proto__ = NULL//Third judgment L = = NULL//return FALSE

Back to top of page

Brief analysis of the application of instanceof in Dojo inheritance mechanism

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.

Listing 10. Multiple inheritance in Dojo
Dojo.declare ("Aoo", null,{});  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

In the above example, Foo inherits both from Aoo and Boo, but returns false when the instanceof operator is used to check if Foo is an instance of Boo. In fact, within Dojo, Foo is still only inherited from Aoo, and the methods and properties in the Boo class are copied to Foo by the mixin mechanism, so when the instanceof operator is used to check if it is an instance of Boo, it returns false. So Dojo adds a new method for each instance of the class called Isinstanceof, which is used to check for multiple inheritance.

Conclusion

This article describes in detail the instanceof operator in the JavaScript language and analyzes the algorithm of this operator in depth with the language specification. It can be a great help for readers to write complex object-oriented programs using JavaScript. All the code in this article was tested under Firefox 15.

ResourcesLearn
    • For Dojo, please refer to the Official Dojo website

    • DeveloperWorks Web Development Zone: Extend your skills in web development with articles and tutorials dedicated to web technology.

    • DeveloperWorks Ajax Resource Center: This is a one-stop center for information about AJAX programming models, including many documents, tutorials, forums, blogs, wikis, and news. Any new Ajax information can be found here.

    • The DeveloperWorks Web 2.0 Resource Center, a one-stop Center for Web 2.0-related information, includes a large number of Web 2.0 technical articles, tutorials, downloads, and related technical resources.


JavaScript instanceof operator in-depth anatomy

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.