In the article "JavaScript type Detection", which mentions the use of instanceof as a test type, let's review:
So how did Instanceof's behavior come true, and now let's uncover the fog behind instanceof.
instanceof principle
As a rule, let's look at a piece of code first:
12345678910111213141516171819202122232425 |
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:
The memory diagram is quite complex and explains:
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 changes of these three prototype references. In the heap, the right side is the memory representation of the function object, the middle is the pointer to the prototype property of the function object, and to the left is the object instance created by the function object. The pointer to the prototype property in which the function object is written dog1,dog2,dog3 the three reference changes corresponding to 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 blog post)
One thing to note is that the prototype property of the function object in Dog3 is null, and the internal [[prototype]] property of the Function object instance dog3 points to Object.prototype, which is in the understanding javascript_06_ Understanding the object creation process has been explained.
Conclusion
According to the code running result and memory structure, the conclusion is deduced:
Instanceof detects if an object A is an instance of another object B by looking at whether the object pointed to by prototype of Object B is on the [[prototype]] chain of object A. Returns true if it is, or false if it is not. There is a special case, however, when the prototype of object B is null, it will be an error (similar to a null pointer exception).
Here to recommend an article, from the years as a song, but also about the principle of instanceof, the angle is different, but there are similar to the wonderful.
1 |
http://lifesinger.org/blog/2009/09/instanceof-mechanism/ |
Understanding Javascript_07_ Understanding instanceof Realization Principle "turn"