简体   繁体   中英

How to check instanceof class that is defined within a function?

I am trying to export a class that is defined within a function. So, I tried declaring a class export like this:

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

No errors are created everything seems fine. Now I want to check somewhere else if the item is an instance of that exported definition like this:

export class CameraService {
  constructor() {
    const cam = Engine.gameObjects.find(o => o instanceof GameCameraComponent && o.isMainCamera);
  }
}

Now at this point, I get the two following errors (I believe this is from webpack as there are no errors in the vscode editor):

export 'GameCameraComponent' (imported as 'GameCameraComponent') was not found in '../decorators' (possible exports: Camera, GameObject, ObjectChild, ObjectChildren, Path, Prefab)

Next, in the chrome console I get this error:

Uncaught TypeError: Right-hand side of 'instanceof' is not an object

How can I see if the item is an instanceof the inner function class?

Instanceof validates if an object is created by a class. Only passing the same name in the return is not valid. The following though, is possible:

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

The return type now equals instanceof GameCameraComponent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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