【问题标题】:typescript class cannot find "this" variable?打字稿类找不到“this”变量?
【发布时间】:2015-12-16 23:48:28
【问题描述】:

我正在使用 babylonjs 库并使用打字稿创建了一个“建筑”类。顺便说一句,对整个事情使用打字稿。我从我的主 game.ts“游戏”类创建了这个新的“建筑”,当尝试访问“建筑”的成员时,我得到“未定义”的变量错误。然而,这只发生在另一个类方法中,但似乎在构造函数中正常工作。我假设它与 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++
      });
    }
}

【问题讨论】:

    标签: javascript typescript babylonjs


    【解决方案1】:

    我猜你快到了。箭头函数(=&gt;)语法是我们需要的,但即使在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
    });
    

    【讨论】:

    • 我明白了.. 所以我想当你创建一个匿名函数时,它不知道要使用哪个“this”.. 文档还是类?我在正确的轨道上吗?试图解释这一点,所以如果有人查了这个,他们就会明白为什么它会起作用。不过感谢您的帮助,这行得通。我会将其标记为已修复。
    • @efel 如果您正在创建一个简单的匿名函数,上下文(this 关键字)将始终是全局范围(通常,在浏览器中,全局范围是 window 对象) .当您使用箭头函数时,上下文将始终与您已经存在的上下文相同,因此,如果您在类的方法中,则上下文将是对象(该类的实例),而箭头函数的上下文将是相同的。以前,当没有箭头函数时,解决方法是创建一个局部变量来~保存~上下文,然后在匿名函数中使用它。
    • 我用来解释它的方式是——TS 编译器将创建var _this = this;,然后在生成的箭头函数=&gt; 中使用它。所以,外面的 this 现在变成了里面的 this……阅读更多关于箭头函数的内容……让它变得更加清晰 ;)
    猜你喜欢
    • 2021-11-10
    • 1970-01-01
    • 2022-01-06
    • 2018-01-16
    • 2013-04-15
    • 1970-01-01
    • 1970-01-01
    • 2020-05-02
    相关资源
    最近更新 更多