【发布时间】:2018-10-19 17:35:32
【问题描述】:
下面是我在 Javascript 中的代码。我需要在 Angular 组件内的组件类中编写它。
根据我的理解,Character.prototype.placeAt() 代码向现有对象添加了新方法或属性。或者,在这种情况下,placeAt() 内的this.tile = tileTo; 将使用全局 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>
我尝试将其转换如下,但我无法在 typescript 类中使用 Character.prototype,因为我收到错误:'duplicate identifier Character'。那么如何将placeAt() 添加到 Character 对象中呢?
是否可以在不使用 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 的新手。
【问题讨论】:
-
了解 TypeScript 类语法的基础知识。 typescriptlang.org/docs/handbook/classes.html
-
不要使用
any。 -
您应该为所有字段和参数声明类型。
-
@SLaks 我会关注那些 cmets。谢谢你。但这些都不是最终答案吧!
-
发生该错误是因为您的类语法没有意义。您需要遵循 TypeScript 语法。
标签: javascript angular typescript