簡體   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