typescript class 找不到 "this" 变量?

typescript class cannot find "this" variable?

我正在使用 babylonjs 库并使用 typescript 创建了一个 "Building" class。顺便说一句,整个事情都使用打字稿。我从我的主 game.ts "Game" class 创建了这个新的 "Building" ,当试图访问 "Building" 的成员时,我得到 "undefined" 变量错误。然而,这只发生在另一个 class 方法中,但似乎在构造函数中工作正常。我假设它与 javascript/typescript 中的 "this" 范围界定有关。我尝试通过以下方式修改函数:

Create = ...(...)=> {
   ...

我尝试通过以下方式创建变量:

private rect: = () => Rectangle

但这仍然不起作用

这真的是 "this" 范围界定的问题吗,因为似乎没有任何效果。 下面我准确地标记了这个变量在哪里起作用,哪里不起作用。

class Building {

    private rect : Rectangle
    private buildingMesh:string[]
    private buildingId:string

    constructor(rect: Rectangle, id:string) {

      this.rect = rect
      console.log("TL in b const: " + this.rect.topLeft.x) // <--- This works here
      this.buildingId = id

    }

    Create(scene:BABYLON.Scene) {

      BABYLON.SceneLoader.ImportMesh(this.buildingId, "models/","tree.babylon", scene, function (newMeshes) {

          var idx = 0

          console.log("TL in b: " + this.rect.topLeft.x) // <--- this gives me undefined
          var wall =newMeshes[0].createInstance(this.buildingId + idx) 
          wall.position.x = this.rect.topLeft.x
          wall.position.y = this.rect.topLeft.y
          this.buildingMesh.push(this.buildingId + idx)
          idx++
      });
    }
}

我猜你快到了。箭头函数 ( => ) 语法是我们需要的,但即使在 BABYLON.SceneLoader.ImportMesh 调用上:

BABYLON.SceneLoader
    .ImportMesh(this.buildingId, "models/","tree.babylon", scene, 
        function (newMeshes) {
         ...
         // here we do not have this kept by TS for us
});

我们应该使用

BABYLON.SceneLoader
    .ImportMesh(this.buildingId, "models/","tree.babylon", scene, 
        (newMeshes) => {
         ...
         // here the magic would happen again
         // and compiler will keep this to be what we expect
});