Parsing JavaScript instanceof may return true for different constructors

Source: Internet
Author: User
Tags constructor inheritance

  This article is mainly on JavaScript instanceof for different constructors may return true for detailed analysis, the need for friends can come to the reference, I hope to help you.

We know that the instanceof operator is used to check whether an object is an instance of a constructor. The following lists the various scenarios in which it returns true.   1, Object obj was created through new constructor, then obj Instanceof constructor is true     code as follows: function person (n, a) {      THIS.name = n;      this.age = a; }  var p = new Person (' John Backus ',);  Console.log (P instanceof person); true    2, if an inheritance relationship exists, the subclass instance instanceof the parent class also returns A True code as follows: Function A () {}  function B () {}  B.prototype = new A (); b inherits from a    var b = new B ();  Console.log (b instanceof A); true    3, because object is the root class, all other custom classes inherit from it, so the instance instanceof object of any constructor returns true the copy code code is as follows: function A () {}  VA R A = new A ();  Console.log (a instanceof Object); true    var str = new String (' Hello ');  console.log (str instanceof Object); true    var num = new Number (1);  console.log (num instanceof Object); true    Even includes the constructor's own code as follows: function A () {}  Console.log (a instanceof Object); True  Console.log (String instanceof Object); true  console.log (number instanceof Object); true    4, all constructors instanceof function returns a true code as follows: function A () {}  console.log (a instanceof function); true  Console.log (String instanceof Function); true  console.log (number instanceof Function); true    above four points is summed up as a sentence: If an instance is created from a class or its subclasses, then Instanceof returns True. Or the prototype of a constructor exists on the inner prototype chain of object obj, and returns True. That is, the result of instanceof is not directly related to the constructor itself. This is common in many languages.   Java defines a class person, instance p returns true for person and object     code as follows: Class person {      public String NA me;      public int age;      person (String n, int a) {          T His.name = name;          This.age = a;     }      public static V OID Main (string[] args) {          person p = new person ("John Backus",);          SYSTEM.OUT.PRINTLN (p instanceof person); true          SYSTEM.OUT.PRINTLN (P instanceof Object); true     } }    Java If an inheritance relationship exists, the subclass instance instanceof the parent class also returns true code as follows://parent class   class per Son {      public String name;      public int age;      person (String N, T a) {          name = name;          age = a;     }&NBS P } //Subclass   public class Mans extends person{      public String university;      Mans (string n, int a, String s) {          super (n, a);          University = s;     }&N Bsp     public static void main (string[] args) {          mans mm = new Man ("John Resig", 29 , "PKU");          SYSTEM.OUT.PRINTLN (mm instanceof man); true          SysTem.out.println (mm instanceof person); Also true     } }    know these, JS in the following performance is not surprising the copy code code is as follows://define two constructors   function A () {}  function B () {}  a.prototype = B.prototype = {a:1};   //Create two instances of different constructors   var a = new A ();  var b = new B ();  Console.log (a instanceof B); true  Console.log (b instanceof A); true    We see A, B are created with A and b respectively, but a instanceof B and B instanceof A are all true. That is, a is not created with constructor B, but still returns true. Because B.prototype exists on the internal prototype chain of a.   Because of the dynamic language characteristics of JS, you can modify the prototype at run time, so it is not surprising to return false below. The chain is interrupted because A.prototype is no longer in the internal prototype chain of a.     Code is as follows: function A () {}  var a = new A ();  a.prototype = {}; Dynamic modification of the prototype, note must be created after the creation of a   console.log (a instanceof a); false    Note It also breaks the first article that is summarized above: Object obj is created by the new constructor, then obj Instanceof constructor is true   In fact, in the ECMAScript Standard (5.1), instanceof internal implementation invokes the internal method of the constructor [[[Hasinstance]], described as follows       If f is a function object, when F (V) executes, The following steps occur:   1, if the instanceof left operand V is not an object type, returns false directly   The   code is as follows: var a, B = 1, c = true, d = ' Hello ';  console.log (a instanceof Object); False here a value is undefined  Console.log (b instanceof Object); false  Console.log (c instanceof Object); false  Console.log (d instanceof Object); false    2/3, prototype property of the constructor F, if not the object type, throw the TypeError exception, the code is as follows: function A () {}  a.prototype = 1; The prototype of a is set to be not object type   var a = new A ();  Console.log (a instanceof a);    The exception prompts thrown by each browser are different,   Firefox   CHROME24:   Safari6:   OPERA12:   IE10:   4, continuous execution of the following logic: V to be the internal prototype of V, if V is null then return False if V and O both refer to To the same object, returns True.
Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.