This is my classes:
export class Parent {
protected static name: string;
public getName() {
return Parent.name
}
}
export class Child1 extends Parent {
constructor() {
super()
if (!Child1.name) {
// connect to database for get names
Child1.name = '1';
}
}
}
export class Child2 extends Parent {
constructor() {
super()
if (!Child2.name) {
// connect to database for get names
Child2.name = '2';
}
}
}
I run this code:
let child1 = new Child1()
let child2 = new Child2()
console.log(child1.getName())
console.log(child2.getName())
And I get this result:
undefined
undefined
But I get this result:
1
2
I want to connect to database and get names
, so per new class
I dont want to connect to database again.
CodePudding user response:
Parent.name
will always access the name
property of Parent
. If you want to make it conditional on which instance the function is called on you have to use this.constructor.name
instead:
public getName() {
return this.constructor.name
}
this.constructor
refers to the object's constructor function / class.
class Parent {
getName() {
return this.constructor.db
// ^^^^^^^^^^^^^^^^
}
}
class Child1 extends Parent {
constructor() {
super()
if (!Child1.db) {
// connect to database for get names
Child1.db = '1';
}
}
}
class Child2 extends Parent {
constructor() {
super()
if (!Child2.db) {
// connect to database for get names
Child2.db = '2';
}
}
}
let child1 = new Child1()
let child2 = new Child2()
console.log(child1.getName())
console.log(child2.getName())
CodePudding user response:
The problem is static members are bound to the class and can not be referenced via an instance.
Use it like this:
class Parent {
protected static name: string;
public getName() {
return Parent.name
}
}
class Child1 extends Parent {
constructor() {
super()
if (!Parent.name) {
Parent.name = '1';
}
}
}
class Child2 extends Parent {
constructor() {
super()
if (!Parent.name) {
// connect to database for get names
Parent.name = '2';
}
}
}
let child1 = new Child1();
let child2 = new Child2();
console.log(child1.getName());
console.log(child2.getName());
CodePudding user response:
export class Parent {
protected namE: string;
public getName() {
return this.namE
}
}
export class Child1 extends Parent {
constructor() {
super()
if (!this.namE) {
// connect to database for get namEs
this.namE = '1';
}
}
}
export class Child2 extends Parent {
constructor() {
super()
if (!this.namE) {
// connect to database for get namEs
this.namE = '2';
}
}
}
let child1 = new Child1()
let child2 = new Child2()
console.log(child1.getName())
console.log(child2.getName())
OutPut:
1
2
Why don't you do it this way?