So how instanceof this behavior is actually achieved, now let us uncover the fog behind instanceof.
instanceof Principle
As a rule, let's take a look at a code:
Copy Code code as follows:
function Cat () {}
Cat.prototype = {}
function Dog () {}
Dog.prototype ={}
var dog1 = new Dog ();
Alert (dog1 instanceof Dog);//true
Alert (dog1 instanceof Object);//true
Dog.prototype = Cat.prototype;
Alert (dog1 instanceof Dog);//false
Alert (dog1 instanceof Cat);//false
Alert (dog1 instanceof Object);//true;
var dog2= new Dog ();
Alert (dog2 instanceof Dog);//true
Alert (dog2 instanceof Cat);//true
Alert (dog2 instanceof Object);//true
Dog.prototype = null;
var dog3 = new Dog ();
Alert (Dog3 instanceof Cat);//false
Alert (Dog3 instanceof Object);//true
Alert (Dog3 instanceof Dog);//error
Let's draw a memory graph to analyze:
Memory diagram is more complex, explain:
The program itself is a dynamic concept, with the implementation of the program, Dog.prototype will continue to change. But for the sake of convenience, I only drew a picture to express the change of the three prototype references. In the heap, the right side is the memory representation of the function object, the middle is the point of the prototype property of the function object, and the left is the object instance created by the function object. Where the function object points to the prototype property, it writes dog1,dog2,dog3 three reference changes corresponding to the Dog.prototype respectively. They also have a corresponding relationship with the dog1,dog2,dog3 in the stack. (Note: About function objects will be explained in subsequent posting)
One thing to be aware of is that the prototype property of a function object in Dog3 is null, and the internal [[prototype]] property of the Function object instance dog3 points to object.prototype, in the understanding javascript_06_ The process of understanding the creation of objects has been explained.
Conclusion
According to the code running result and memory structure, the conclusion is deduced:
Instanceof the principle of detecting whether an object A is an instance of another object B is to see if object B's prototype points to an object on the [[prototype]] chain of object A. Returns true if it is, or false if not. In a special case, however, an error occurs when object B's prototype is null (similar to a null-pointer exception).
Here recommend an article, from the years, such as song, but also on the principle of instanceof, different angles, but the same as the wonderful.