Issue
I'm working with typescript and I have a problem with the static inheritance between classes
Can anyone explain me the result of the following :
class Foo {
protected static bar: string[] = [];
public static addBar(bar: string) {
this.bar.push(bar);
}
public static logBar() {
console.log(this.bar);
}
}
class Son extends Foo {
protected static bar: string[] = [];
}
class Daughter extends Foo {}
Foo.addBar('Hello');
Son.addBar('World');
Daughter.addBar('Both ?');
Foo.logBar();
Son.logBar();
Daughter.logBar();
current result :
[ 'Hello', 'Both ?' ]
[ 'World' ]
[ 'Hello', 'Both ?' ]
but I want :
[ 'Hello' ]
[ 'World' ]
[ 'Both ?' ]
Do I have a solution without redeclare the static bar
property ?
Thanks !
Solution
A very detailed explanation of the behavior in the OPs code is found in answer in this thread by @T.J.Crowder.
To avoid the need to redefine the static member you can take this approach:
class Foo {
private static bar = new Map<string, string[]>();
public static addBar(bar: string) {
let list: string[];
if (this.bar.has(this.name)) {
list = this.bar.get(this.name);
} else {
list = [];
this.bar.set(this.name, list);
}
list.push(bar);
}
public static logBar() {
console.log(this.bar.get(this.name));
}
}
class Son extends Foo {}
class Daughter extends Foo {}
Foo.addBar('Hello');
Son.addBar('World');
Daughter.addBar('Both ?');
Answered By - Nitzan Tomer
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.