繁体   English   中英

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

[英]Access a object's class's static methods in Typescript?

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 的确切 class,我需要打印 A 或只调用f()以获得正确的 obj 的 class。

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

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

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; }

注意 static 属性存在于类中,但不存在于实例中。

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

.prototype属性仅存在于函数中,并且当使用new实例化新的 object 并调用该构造函数 function ( 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM