First, topic introduction
In my last article, I briefly talked about THE JS prototype chain, and here I would like to elaborate another idea. I think: To really explore the specific relationship between Function and Object in JS is like exploring the relationship between the chicken and the egg. In fact, it is difficult for us to determine the two: Which of the following is an instance of which, and which of the following is a constructor of which?
Like Linus Torvalds, the founder of Linux: Talk is cheap. Show me the code.
The instanceof operator is used to check whether the constructor’s prototype property is present in the prototype chain of an instance object
console.log(Object instanceof Function);
console.log(Function instanceof Object);
Copy the code
I don’t know if you have printed the result of two lines of code in your mind. In fact, I have explained the result just now, so let me explain why:
Instanceof principle analysis
We certainly can’t create an internal keyword like Instanceof to do this, but we can use functions to simulate the process. Simply put, instanceof works as the definition says: The prototype property of the constructor is searched for on the prototype chain of the tested Object. This process is carried along the prototype chain until the very top of the prototype chain is found. If Object is not found, null is returned, indicating that the Object is not an instance of the constructor.
// The instance_of function is used to simulate the instanceof function
// It takes two arguments, the first being the object to be tested, obj, and the second the constructor to be tested
function instance_of(obj, constructor) {
let prototype = constructor.prototype;
// Use an API defined on Object => getPrototypeOf
// It is used to return the value of the current object's prototype
let proto = Object.getPrototypeOf(obj);
while(true) {
// Return null if the prototype attribute is not found in the entire prototype chain
if(proto === null) {
return false;
}
// If the current prototype object contains the prototype property, it returns true
else if(proto === prototype) {
return true;
}
// Each loop returns the prototype of the current object
// The prototype object passed in as obj is returned first, and then every object in the prototype chain
proto = Object.getPrototypeOf(proto); }}Instance_of = instance_of; instanceof = instance_of
console.log(instance_of(Function.Object));
console.log(instance_of(Object.Function));
console.log(Function instanceof Object);
console.log(Object instanceof Function);
Copy the code
As for the output of four lines, which of course is four true, you can go to the browser console and try it out
Third, summary
The above content is the author’s understanding of the principle of Instanceof. If there is any problem, I hope you can correct it more, thank you!