I don't understand why fooA and fooB outcome different.
var foo = function(){}
fooA = new foo();
foo.prototype.x = 1;
foo.prototype = { y: 2, z: 3};
console.log(fooA.x, fooA.y, fooA.z);// 1, undefined, undefined
fooB = new foo();
console.log(fooB.x, fooB.y, fooB.z);// undefined, 2, 3
does foo.prototyp = {} override the method defined in front of it?
Why fooA is state in front of prototype.x, it inherit the result, but not y and z?
__proto__ is a way to inherit properties from an object in JavaScript. __proto__ a property of Object. prototype is an accessor property that exposes the [[Prototype]] of the object through which it is accessed. POSTly is a web-based API tool that allows for fast testing of your APIs (REST, GraphQL).
The __proto__ property is a default property added to every object. This property points to the prototype of the object. The default prototype of every object is Object. prototype . Therefore, the __proto__ property of the person object points to the Object.
In reality, the only true difference between prototype and __proto__ is that the former is a property of a class constructor, while the latter is a property of a class instance.
prototype is a property of a Function object. It is the prototype of objects constructed by that function. __proto__ is an internal property of an object, pointing to its prototype. Current standards provide an equivalent Object.
The reason for that behavior is that you make foo.prototype point to a new object when using foo.prototype = { y: 2, z: 3};, and existing objects' prototypes don't change when the constructor's prototype property is set to a new value.
A line-by-line explanation of what happens:
var foo = function(){}
foo.prototype is initialized as an empty object (we shall call this object A).
fooA = new foo()
fooA is set to a new foo object, it has its prototype set to foo.prototype (A).
foo.prototype.x = 1
Because fooA's prototype is the same object as foo.prototype, fooA.x becomes 1. In other words, A gets the property x = 1.
foo.prototype = { y: 2, z: 3};
We create a new object that has the properties y = 2 and z = 3. We shall call this object B. foo.prototype is set to the new object.
console.log(fooA.x, fooA.y, fooA.z);
fooA's prototype is still A, which only has the x = 1 property.
fooB = new foo();
We create a new foo object whose prototype is B.
console.log(fooB.x, fooB.y, fooB.z);
fooB's prototype is B, which has the properties y = 2 and z = 3, but not the property x.
Consider
var foo = function(){}
fooA = new foo();
foo.prototype.x = 1;
console.log(fooA.__proto__) // {x:1}
foo.prototype = { y: 2, z: 3};
console.log(fooA.__proto__) // still {x:1}
An object's prototype is assigned at creation time (when calling new) and doesn't change afterwards.
See here for details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With