Issue
Hi all I m new to ES6 classes , currently want to inherit initiated object(this._obj) with updated data, but in the class B i m getting length of initiated object not the updated object?
class A {
constructor() {
//intiating array of object with length 0
this._obj = new Object();
this._obj['abarray'] = [];
}
_renderData() {
let datas = {
id: 1,
name: 'abc',
};
this._obj['abarray'].push(datas);
console.log(this._obj);
//output
/*{abarray: Array(1)}
abarray: Array(1)
0: {id: 1, name: "abc"}
length: 1
__proto__: Array(0)
__proto__: Object
*/
}
}
const a = new A();
a._renderData();
class B extends A {
constructor() {
super();
}
_showObjectData() {
//here i want to get the updated object with length 1 as shown in output but i getting as intialized
/*
{abarray: Array(0)}
abarray: Array(0)
length: 0
__proto__: Array(0)
__proto__: Object
*/
console.log(this._obj);
}
}
const b = new B();
b._showObjectData();
Please any one can help how to achieve this...
Solution
Calling _renderData
on an instance of A
doesn't effect other instances of either A
or B
, if you want to call _renderData
for every instance of B
, make that call in the constructor itself, otherwise call it on individual instances of B
.
In the following code snippet, I've created another instance of A
and stored it in variable a1
, now if you log a1._obj
it wouldn't be same as a._obj
.
class A {
constructor() {
this._obj = new Object();
this._obj["abarray"] = [];
}
_renderData() {
let datas = { id: 1, name: "abc" };
this._obj["abarray"].push(datas);
}
}
const a = new A();
a._renderData();
console.log("a", a._obj);
// Another instance of "A"
const a1 = new A();
console.log("a1", a1._obj); // a1._obj is not same as a._obj
Calling it in the constructor
of B
.
class A {
constructor() {
this._obj = new Object();
this._obj["abarray"] = [];
}
_renderData() {
let datas = { id: 1, name: "abc" };
this._obj["abarray"].push(datas);
}
}
const a = new A();
a._renderData();
console.log("a", a._obj);
class B extends A {
constructor() {
super();
this._renderData();
}
_showObjectData() {
return this._obj;
}
}
const b = new B();
console.log("b", b._showObjectData());
Calling it on an instance of B
.
class A {
constructor() {
//intiating array of object with length 0
this._obj = new Object();
this._obj["abarray"] = [];
}
_renderData() {
let datas = { id: 1, name: "abc" };
this._obj["abarray"].push(datas);
}
}
const a = new A();
a._renderData();
console.log("a", a._obj);
class B extends A {
constructor() {
super();
}
_showObjectData() {
return this._obj;
}
}
const b = new B();
b._renderData();
console.log("b", b._showObjectData());
Answered By - Som Shekhar Mukherjee
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.