以下是我在Javascript中拥有的代码。我需要在Angular组件内的组件类中编写此代码。
根据我的理解,Character.prototype.placeAt()
代码向现有对象添加了新的方法或属性。或者,在这种情况下,this.tile = tileTo;
中的placeAt()
将使用全局tileTo变量更新Character Object的实例。但是如何将其转换为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>
我尝试如下进行转换,但是由于出现错误:“重复标识符字符”,因此无法在打字稿类中使用Character.prototype
。那么如何将placeAt()
添加到Character对象?
是否可以在不使用此变量或不发送类实例的情况下访问类变量?由于这会随上下文而改变,即在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的新手。
答案 0 :(得分:1)
字符应该是具有属性和方法的自己的类。看起来像这样:
character.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);
}
}
或者,如果您的字符始终从同一位置开始,则可以在Character
类中设置这些值,并且在创建新字符时不必传递这些值。