Javascript 如何从类外访问类函数,相同的.ts文件
我有一个与相3库的游戏。此游戏位于文件Javascript 如何从类外访问类函数,相同的.ts文件,javascript,angular,typescript,components,phaser-framework,Javascript,Angular,Typescript,Components,Phaser Framework,我有一个与相3库的游戏。此游戏位于文件phaser game.component.ts中。其中的类用于与其他组件和服务交互。游戏的功能在此文件中,但不在类中。我需要从phaser game.component.ts文件访问类中的特定方法,或类的scoreService属性。我如何引用它们呢 1) 类内(首选)的函数,该函数来自类外和同一文件或 2) 从类外和同一文件中获取的类的分数(typeof“ScoreService”) -将这些属性称为“this.updateHighscore” -在类外
phaser game.component.ts
中。其中的类用于与其他组件和服务交互。游戏的功能在此文件中,但不在类中。我需要从phaser game.component.ts
文件访问类中的特定方法,或类的scoreService
属性。我如何引用它们呢
1) 类内(首选
)的函数,该函数来自类外和同一文件或
2) 从类外和同一文件中获取的类的分数(typeof“ScoreService”
)
-将这些属性称为“this.updateHighscore”
-在类外部声明新的scoreService
,以访问所需的函数
-将代码移动到.html
文档中的脚本标记,而不是关联的.ts
文件
Phaser-game.component.ts:
如果需要任何其他代码,请告诉我。就我所能测试的而言,一切都按预期进行,我只是无法访问该文件中类中的updateHighscore
。谢谢
预期成果:
PhaserGameComponent类下的updateHighscore函数成功地从构造函数中声明的scoreService调用了updateHighscore函数
实际结果:
我所尝试的一切都无法访问PhaserGameComponent类下的updateHighscore函数。通常
“X是未定义的”
,“X”是我用来尝试实现该功能的任何东西。这将不起作用,typescript将被转换为javascript,angular cli将在构建时删除游戏循环,我建议编写一个GameLoopComponent
使用PhaserGameComponent
的方法,然后你可以调用updateHighscore
方法,如果你有PhaserGameComponent实例化的参考,我会尝试,谢谢你,这不起作用,类型脚本将被转换成javascript,angular cli将在构建时删除游戏循环,我建议编写一个GameLoopComponent
,它使用PhaserGameComponent
,然后您可以调用updateHighscore
方法,如果您有PhaserGameComponent实例化的参考,我将尝试一下,谢谢
import { ApiService } from './../api.service';
import { ScoreService } from './../score.service';
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Physics } from 'phaser';
@Component({
selector: 'app-phaser-game',
templateUrl: './phaser-game.component.html',
styleUrls: ['./phaser-game.component.css']
})
export class PhaserGameComponent implements OnInit, OnDestroy {
user: any;
constructor(private api: ApiService, private score: ScoreService) {}
ngOnInit() {
game = new Phaser.Game(config);//Makes game
console.log("Component loaded");//Debug
this.api.getUser().subscribe(res => {//This works, gets user data
res == {} ? (
this.user = this.api.getUser().subscribe(res => {
this.user = res;
})
) : this.user = res;
});
}
ngOnDestroy(): void {
console.log("component being destroyed");
game.destroy();
moveSpeed = 200;
}
//This is the function that needs to be accessed
updateHighscore(): void {
this.score.updateHighscore(dataToSend);//This function works
}
}
//End of class
/*
Bunch of code relating to function of the game
*/
//This is the method that needs to do the update
//It's the games loop
update() {
if (gameOver) {
//Somehow get to the updateHighscore() method
return; //This ends the game loop
}
}