This article I will start from the concept and the corresponding topic knowledge points, I hope you can gain something

A prototype,

① All reference types have a _proto_(implicit stereotype) attribute (similar to the next pointer in a linked list), which can access the next element through.next, and the element above it through._proto_.

② All classes have a prototype property, e.g. Object,Function,Array

The _proto_ attribute of all reference types refers to the prototype of its constructor. For example, if arr is an Array instance, then arr._proto_= array.prototype

Second, prototype chain

When accessing an attribute of an object, it looks for the object itself. If not, it looks for its _proto_ constructor. If not, it looks for its _proto_ constructor. And so you go up layer by layer and you create a chain, which we call a prototype chain.

The following example will help you understand the prototype chain:

Arr is an instance of Array

arr._proto_=Array.prototype

Array._proto_=Object.prototype

Analysis: Object. Prototype: arr._proto_._proto_. It’s just that _proto_ is looking up.

Interview question:

If A can find b. prototype along the prototype chain, then an instanceof B is true(use _proto_ to find).

Solution: Iterate through the prototype chain of A, returning true if b. prototype is found, false otherwise

const instanceof =(A,B) = >{
    let p = A;
    while(p){
        if(p === B.prototype){
            return true;
        }
        p = p._proto_;
    }
    return false;
}
Copy the code


Topic 2:

var foo = {}, F = function(){};

Object.prototype.a = ‘value a’;

Function.prototype.b = ‘value b’;

console.log(foo.a); console.log(foo.b); console.log(F.a); console.log(F.b); Analysis: If the X attribute is not found on the A object, then the x attribute is searched along the prototype chain. (If A is an instance of A Function, then you can’t find it on the class. If you can’t find it on the class, then you can find it on the class.)

Solution: Specify the stereotype chain for variables foo and F, and find attributes A and B along the stereotype chain

So the answer is:

'value a'
'undefined'
'value a'
'value b'
Copy the code

Foo does not have the b attribute because the prototype chain cannot be traced down, but up, to the point where an instance cannot ask its child Function if it has the B attribute attached








If you find this article helpful, please don’t forget to follow it

Your support is the biggest motivation for me!

Will continue to work hard code more fine articles!!