Javascript typescript类找不到“;这";变量
我正在使用babylonjs库,并用typescript创建了一个“Building”类。顺便说一句,我从我的主game.ts“game”类中创建了这个新的“Building”,当尝试访问“Building”的成员时,我得到了“undefined”变量错误。然而,这只发生在另一个类方法中,但在构造函数中似乎工作正常。我假设这和javascript/typescript中的“this”作用域有关。我已尝试通过以下操作修改该函数:Javascript typescript类找不到“;这";变量,javascript,typescript,babylonjs,Javascript,Typescript,Babylonjs,我正在使用babylonjs库,并用typescript创建了一个“Building”类。顺便说一句,我从我的主game.ts“game”类中创建了这个新的“Building”,当尝试访问“Building”的成员时,我得到了“undefined”变量错误。然而,这只发生在另一个类方法中,但在构造函数中似乎工作正常。我假设这和javascript/typescript中的“this”作用域有关。我已尝试通过以下操作修改该函数: Create = ...(...)=> { ... 我
Create = ...(...)=> {
...
我已尝试通过以下方式创建变量:
private rect: = () => Rectangle
但这仍然不起作用
这真的是“这个”范围界定的一个问题吗?因为似乎什么都不起作用。
下面我准确地标记了这个变量在哪里工作,在哪里不工作
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++
});
}
}
班级建设{
私有矩形:矩形
私有buildingMesh:string[]
私有buildingId:string
构造函数(rect:Rectangle,id:string){
this.rect=rect
console.log(“b const中的TL:+this.rect.topLeft.x)/我想你差不多到了。箭头函数(=>
)语法是我们需要的,但即使在巴比伦.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
关键字)将始终是全局范围(通常,在浏览器中,全局范围是窗口
对象)。当您使用箭头函数时,上下文将始终与您现有的上下文相同,因此,如果您在类的方法中,则上下文将是对象(该类的实例),并且arrow函数的上下文将是相同的。以前,当没有arrow函数时,解决方法是创建一个局部变量来~save~上下文,然后在annonymous函数中使用它。我用来解释它的方法是-TS编译器将创建var\u this=this;
,然后在生成的arrow f中使用它function=>
。所以,外面的是什么,现在里面的是什么……阅读更多关于箭头函数的内容……让它变得更清楚;)