这是我的类:
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';
}
}
}
我运行这个代码:
let child1 = new Child1()
let child2 = new Child2()
console.log(child1.getName())
console.log(child2.getName())
我得到的结果是:
undefined
undefined
但我得到的结果是:
1
2
我想连接到数据库并获得names
,所以根据new class
,我不想再连接到数据库。
Parent.name
将始终访问Parent
的name
属性。如果你想让它以调用函数的实例为条件,你必须使用this.constructor.name
:
public getName() {
return this.constructor.name
}
this.constructor
是指对象的构造函数/类。
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())
问题是静态成员绑定到类,不能通过实例引用。
这样使用:
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());
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())
输出:
1
2
你为什么不这样做?