【问题标题】:Access a object's class's static methods in Typescript?在 Typescript 中访问对象的类的静态方法?
【发布时间】:2019-10-29 00:22:23
【问题描述】:
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似乎都是语法错误。

【问题讨论】:

  • 您是否保证objAB 的实例?
  • Object.getPrototypeOf(obj).constructor.f(); 为我工作
  • obj.constructor.f() 肯定不是语法错误。你的意思是你得到一个类型错误?如果有,是哪一个?
  • Typescript 认为obj.constructorFunction,因此会显示错误,但在转换为&lt;any&gt; 时可以正常工作。 Object.getPrototypeOf(obj).constructor.f() 工作。

标签: javascript typescript class static static-methods


【解决方案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

【讨论】:

  • 谢谢,这些解决方案有效。 Typescript 认为 obj.constructorFunction 因此显示错误,但在转换为 &lt;any&gt; 时可以正常工作。
猜你喜欢
  • 1970-01-01
  • 2018-04-07
  • 1970-01-01
  • 2020-05-07
  • 2013-04-18
  • 2023-03-07
  • 2013-09-04
  • 2016-02-25
  • 2017-01-13
相关资源
最近更新 更多