Im studing javascript chaining but i cant set constructor deep as i want.
function a() {}
function b() {}
function c() {}
a.prototype.text1 = 'text1';
b.prototype.text2 = 'text2';
c.prototype.text3 = 'text3';
a.prototype.constructor = b;
b.prototype.constructor = c;
var foo = new a();
console.log(foo.text1) // it`s output 'text1'. yea~ it`s right!
// But...
console.log(foo.text3) // it`s output undefined. My intention was output 'test3'.
Why is this happening? What can I do?
please help. thanks.
You can use Object.create().
function a() {}
function b() {}
function c() {}
c.prototype.text3 = 'text3';
b.prototype = Object.create(c.prototype);
b.prototype.text2 = 'text2';
a.prototype = Object.create(b.prototype);
a.prototype.text1 = 'text1';
var foo = new a();
console.log(foo.text1);
console.log(foo.text2);
console.log(foo.text3);
Object.create() basically creates an object with its prototype into another object's prototype.
Doing something like a.prototype.constructor = b is merely setting constructor property to b, not adding prototype of b to a at all.
If you understand ES6 syntax, this is easier to understand (although the result is technically not the same):
class C {
constructor(){
this.text3 = 'text3';
}
}
class B extends C {
constructor(){
super();
this.text2 = 'text2';
}
}
class A extends B {
constructor(){
super();
this.text1 = 'text1';
}
}
var foo = new A();
console.log(foo.text1);
console.log(foo.text2);
console.log(foo.text3);
EDIT
Object.assign() is the more appropriate way to do it.
function a() {}
function b() {}
function c() {}
c.prototype.text3 = 'text3';
b.prototype = Object.assign(c.prototype);
b.prototype.text2 = 'text2';
a.prototype = Object.assign(b.prototype);
a.prototype.text1 = 'text1';
var foo = new a();
console.log(foo.text1);
console.log(foo.text2);
console.log(foo.text3);
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