下面是我的 Javascript 代码。我需要将其写入 Angular 组件内的组件类中。
根据我的理解,Character.prototype.placeAt()
代码向现有对象添加新方法或属性。或者,在本例中,placeAt()
内的 this.tile =tileTo;
将使用全局tileTo 变量更新字符对象的实例。但如何将其转换为 Typescript?
<script type="text/javascript">
tileFrom:any = [1, 1];
tileTo = [1, 1];
function Character() {
this.tileFrom = [1, 1];
this.tileTo = [1, 1];
this.tile = tileTo;
}
Character.prototype.placeAt = function (x, y) {
this.tileFrom = [x, y];
this.tileTo = [x, y];
this.tile = tileTo;
};
var player = new Character();
player.placeAt(..);
</script>
我尝试按如下方式对其进行转换,但无法在 typescript 类中使用 Character.prototype
,因为我收到错误:“重复的标识符字符”。那么如何将 placeAt()
添加到 Character 对象呢?
是否可以在不使用 this 或发送类实例的情况下访问类变量?由于 this 会随上下文而变化,即在 placeAt()
方法中,this
指的是 Character 对象。
export class GametrainComponent implements AfterViewInit {
tileFrom = [1, 1];
tileTo = [1, 1];
Character(self) {
console.log("ss "+self.tileW)
this.tileFrom = [1, 1];
this.tileTo = [1, 1];
this.tile = self.tileTo;
};
Character.prototype.placeAt(x:any, y:any, self) { //error duplicate identifier Character
this.tileFrom = [x, y];
this.tileTo = [x, y];
this.tile = self.tileTo;
};
ngAfterViewInit() {
self = this;
this.player = new this.Character(self);
player.placeAt(..);
}
}
请注意,我是 JavaScript 和 Angular 的新手。
最佳答案
Angular 色应该是它自己的类,具有属性和方法。它看起来像这样:
Angular 色.model.ts:
export class Character {
constructor(
public tileFrom: Tile,
public tileTo: Tile,
public tile: Tile
) {}
placeAt(x, y) {
this.tileFrom = [x, y];
this.tileTo = [x, y];
this.tile = this.tileTo;
}
}
gametrain.component.ts:
import { Character } from 'file/path';
export class GametrainComponent implements AfterViewInit {
player: Character;
constructor() {}
ngAfterViewInit() {
this.player = new Character([1, 1], [1, 1], [1, 1]);
}
moveCharacter(tile: Tile) {
this.player.placeAt(tile);
}
}
或者,如果您的 Angular 色始终从同一位置开始,那么您可以在 Character
类中设置这些值,并且在创建新 Angular 色时不必向其传递值。
关于javascript - 在 Angular4 组件类中将 JavaScript 转换为 TypeScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52897401/