JavaScript instanceof operator in-depth anatomy

Source: Internet
Author: User

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

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 definitions in the 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)).//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, V is the result (2) when the [[Hasinstance]] method of F was called with value V, the following s Teps 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:

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;//The display prototype of R = l.__proto__;//takes the implicit prototype of L 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__;  } }
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

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 L Is there __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 specifications o = Functionr.prototype = Function.prototype L = functionl.__proto__ = function.prototype//First judgment o = = L//return Back to 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 find if L still have __ proto__ L = function.prototype.__proto__ = object.prototype//second judgment o! = L//cycle again to find if l have __proto__ l = Object.prototype . __proto__ = NULL//Third judgment L = = NULL//return FALSE
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.

JavaScript instanceof operator in-depth anatomy

Related Article

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.