angular - 在 ionic 3 中实现 object.prototype.function
问题描述
我在下面的 Javascript 代码中创建了一个对象作为新的 Box2并将每个对象插入到一个数组中。内部循环我在每个元素上调用 draw()。在纯 js 中一切正常,但我想在 ionic 3 中实现此代码。如果在 Ionic 的 .ts 文件中复制相同的代码,在编辑器中它会给出错误:
[ts] Duplicate identifier 'Box2'。[ts] 后续的属性声明必须具有相同的类型。属性“Box2”的类型必须为“() => void”,但此处的类型为“any”。而在浏览器中,它给出的错误是';' 预期为 Box2.prototype 行
Box2() {
this.x = 0;
this.y = 0;
this.w = 1; // default width and height?
this.h = 1;
this.fill = '#444444';
}
Box2.prototype = {
draw : function(){
console.log("hello");
}
}
解决方案
这是一种在带有接口的打字稿中扩展原型的方法。像这样:
class Box2 {
x = 0;
y = 0;
w = 1; // default width and height?
h = 1;
fill = '#444444';
}
interface Box2 { // this interface will allow us to implement draw
draw(): void;
}
Box2.prototype.draw = function() {
console.log("hello");
}
// usage of our draw function
new Box2().draw();
推荐阅读
- javascript - 为什么 clearInterval 在我的代码中不起作用?
- node.js - Antd v4.5.1 为 Select 设置初始值
- mysql - MySQL乘法返回错误结果
- ruby-on-rails - 如何将整数(月)转换为人类友好的字符串?
- pytorch - 使用带有 zarr 的 PyTorch IterableDataset 的内存泄漏问题
- python - 类方法在Python中不返回值
- windows - 安装docker后需要安装kubectl吗?
- ember.js - Ember.js 应用程序中是否可以有一个名为“应用程序”的模型?
- javascript - 使用 .js 和 .jsx 作为 Reactjs 的文件结尾有什么区别?
- bash - 如何通过bash在文本文件中写入执行程序列表