In the code snippet
function a() {}
function b() {
this.uno = "hello"
}
b.prototype = new a();
function c() {
this.dos = "bye"
}
c.prototype = new b();
var obj = new c();
console.log(obj.uno);
console.log(obj.dos);
console.log(obj.constructor);
Lets understand whats happening. When you are doing
b.prototype = new a();
A new instance of a is created and is directly assigned to prototype of b.
So right at this moment if one does
var obj = new b();
The obj.uno will be equal to hello.
Now, when the statement
c.prototype = new b();
is executed, the obj(a instance of the b class) is now assigned to the prototype of c. So right at this moment if one does
var obj = new c();
obj.dos = bye as its assigned in the c constructor class.
obj.uno = 'hello' as it was once assinged while instanciating b constructor.
- As the constructor property is not re-assigned it will still point to the original parent
a. So obj.constructor = function a().
In the second snippet
function a() {}
function b() {
this.uno = "hola"
}
b.prototype = new a();
function c() {
this.dos = "bye"
}
c.prototype = {
constructor: b
}
var obj = new c();
console.log(obj.uno);
console.log(obj.dos);
console.log(obj.constructor);
c.prototype = {
constructor: b
}
is not inheriting b or its prototype chain. In every constructors prototype chain there is aconstructorproperty which points to the constructor class. In the avobe statement, it just reassings it to the functionb`.
UPDATE:
Constructor is a property defined in the prototype chain in any object and as functions are first-class-objects in JS, they too have this property inscribed.
So when you execute the above line, its basically changing the c.prototype.constructor value. And nothing else.
Had you been doing this
c.prototype = {
constructor: 5
}
...
console.log(obj.constructor); // 5.
//Its like setting a value for a property in a JS object.
So when you do:
console.log(obj.constructor);
It points to the newly assigned constructor, i.e. function b().
But as there is no inheritance,
console.log(obj.uno);
is definitely undefined.
However,
console.log(obj.dos);
will be bye when you are creating a new instance of the function c:
var obj = new c();
Hope this helps to understand JS prototypal inheritance in a better way.