![](/img/trans.png)
[英]How to use instanceof with a class which is not defined in the current context?
[英]How to check instanceof class that is defined within a function?
我正在嘗試導出在 function 中定義的 class。 所以,我嘗試像這樣聲明一個 class 導出:
export declare class GameCameraComponent extends GameObject {
isMainCamera: boolean;
}
export abstract class GameObject<T extends { new(...args: any[]): any; } = any> { }
// Used for my decorator
export function Camera(options?: CameraOptions) {
return function (target: new () => object) {
return class GameCameraComponent extends GameObject {
instance = new target();
readonly isMainCamera; // Set in the constructor
}
}
}
沒有錯誤被創建一切似乎都很好。 現在我想在其他地方檢查該項目是否是該導出定義的實例,如下所示:
export class CameraService {
constructor() {
const cam = Engine.gameObjects.find(o => o instanceof GameCameraComponent && o.isMainCamera);
}
}
現在,我收到以下兩個錯誤(我相信這是來自 webpack,因為 vscode 編輯器中沒有錯誤):
export 'GameCameraComponent' (imported as 'GameCameraComponent') was not found in '../decorators' (possible exports: Camera, GameObject, ObjectChild, ObjectChildren, Path, Prefab)
接下來,在 chrome 控制台中,我收到此錯誤:
Uncaught TypeError: Right-hand side of 'instanceof' is not an object
如何查看該項目是否是內部 function class 的實例?
Instanceof 驗證 object 是否由 class 創建。 僅在返回中傳遞相同的名稱是無效的。 但是,以下是可能的:
export class GameCameraComponent extends GameObject {
isMainCamera: boolean;
}
export function Camera(options?: CameraOptions) {
return function (target: new () => object) {
return new GameCameraComponent()
}
}
const myInstance = Camera()()
myInstance instanceOf GameCameraComponent // true
返回類型現在等於instanceof
GameCameraComponent。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.