在Typescript中访问对象类的静态方法?

时间:2019-10-29 00:22:23

标签: javascript typescript class static static-methods

class Base {
  static f(){console.log('Base')}
}

class A extends Base {
  static f(){console.log('A')}
}

class B extends Base {
  static f(){console.log('B')}
}

let obj: A|B = new A()

obj.<what to put here>.f()

我不知道obj的确切类,我需要打印A或仅调用f()以获取obj的正确类。

例如,我不需要类名。 我正在做更复杂的事情。

prototype, typeof, constructor似乎都是语法错误。

1 个答案:

答案 0 :(得分:1)

Object.getPrototypeOf()(替换为现在已弃用的Object.prototype.__proto__)或Object.prototype.constructor均应起作用:

Object.getPrototypeOf(obj).constructor.f();

obj.constructor.f();

实际上:

Object.getPrototypeOf(obj).constructor === obj.constructor; // true

在这里您可以看到正在编译的源代码:

class Base {
  static f() { console.log('Base'); }
}

class A extends Base {
  static f() { console.log('A'); }
}

class B extends Base {
  static f() { console.log('B'); }
}

const objBase = new Base();
const objA = new A();
const objB = new B();

Object.getPrototypeOf(objBase).constructor.f();
objBase.constructor.f();

Object.getPrototypeOf(objA).constructor.f();
objA.constructor.f();

Object.getPrototypeOf(objB).constructor.f();
objB.constructor.f();

console.log(Object.getPrototypeOf(objB).constructor === objB.constructor);
console.log(Object.getPrototypeOf(objB) === B.prototype);
.as-console-wrapper {
  max-height: none !important;
}

请注意,静态属性存在于类中,但不存在于实例中。

因此,如果您想从obj转到其原型,则应该调用Object.getPrototypeOf(obj),而不是obj.prototype,这是完全不同的事情。

.prototype属性仅存在于函数中,并且在使用new实例化新对象并调用该构造函数(new A())时,它将成为新创建的对象的原型(已弃用的.__proto__)。

在您的示例中:

obj.prototype;                // undefined
A;                            // class A { static f() { ... } }
A.protoype;                   // { constructor: class A { ... } }
A.protoype.constructor;       // class A { static f() { ... } }
A.protoype.constructor === A; // true
obj.constructor;              // class A { static f() { ... } }
obj.constructor === A;        // true

Object.getPrototypeOf(obj) === A.prototype; // true
相关问题