Visibility of prototype property of a function vs. object on console
This question already has an answer here:
The property named .prototype
is a property of a constructor function only. It is stored elsewhere for an actual object instance and is not accessible as .prototype
there.
In modern browsers, you can use Object.getPrototypeOf(obj)
to get the prototype of an object instance. See MDN for details.
In some older browsers, you could get to it with obj.__proto__
.
There is no common reason to access the prototype itself on an object instance. It is meant to be the recipe by which new objects are created and THE place to access it is on the constructor as that controls how new objects are created. It is used internally by Javascript on an object instance so it is stored internally. If you're asking why a prototype-based language is designed that way, you're asking the wrong person - that's just how a prototype-based system is designed to be used.
You are meant to interact with the actual property values on an instance of an object, not with the prototype. The central place to access the prototype is via the constructor. There are some special cases of morphing an existing object instance by changing the prototype of an existing instance, but that is not a common design paradigm in prototype-based programming.
In C++ (which is not a prototype-based language, but shares some object oriented concepts), you change the class definition if you want to change how new objects of that type are created. You don't change one instance of a class and expect it to change how new objects of that type are created.
First of all, you are right, every data structure in JavaScript has its own prototype. However, in language grammar level, only function has the prototype
property .
What about others? Well you can't do it with a property key. What you thought of is actually an internal down to the language engine. If you read the ECMAScript spec, you will notice the [[Prototype]] in several sections.
Previously, some browsers provide a __proto__
property, which enables you to access the [[Prototype]], but it's a vendor feature, not part of the spec so unreliable.
Now in ES6 there's a new method for such purpose: Object.getPrototypeOf()
.
One more thing, think about instanceof
operator. It's actually comparing an object's __proto__
to a constructor's prototype
property.
上一篇: 了解原型和这个
下一篇: 控制台上功能与对象的原型属性的可见性