Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
234 views
in Technique[技术] by (71.8m points)

javascript - Why functions prototype is chained repeatedly?

I'm very new to JavaScript. I'm reading from JavaScript good parts. It says :

Every function object is also created with a prototype property

So I did something like this :

function test() {
}

console.log(test.prototype);

Using Chrome's developer tools, I find the output as follows :

enter image description here

I'm really confused with this output. Why does constructor's prototype property again nested with constructor? And why does this goes on like a chain? Where I'm missing the concept?

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The prototype property of a function holds the object from which all instances of that function will inherit when created with the new operator. And all these prototype objects (usually) have a constructor property which points back to the function - there you have the circular reference. So, as a new test() inherits that property, (new test).constructor === test evaluates to true.

You will need to distinguish between the prototype property of a function object and the prototype object from which an object inherits - often referenced as "the internal [[prototype]] property".

A constructor is a function, not to say a Function, and has both. Therefore it inherits from the Function.prototype object - where the constructor property says that all functions are constructed by the Function constructor. If your developers console would show the prototype of Function objects, you could see them. I think there is an option in the settings.

So, the famous "prototype chain" is not about the constructor and/or prototype properties, but about the prototype object from which that object inherits from:

 function test() {}              new test()
   (a Function)              (a test instance)
        ||                           ||
        ||                           ||
        /                           /
 Function.prototype            test.prototype
(a Function, by spec)           (an Object)
        ||                           ||
        ||                           ||
        /                           /
 Object.prototype             Object.prototype
        ||                           ||
        ||                           ||
        /                           /
       null                         null

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...