首页 > 解决方案 > 在 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");
    }
  }

标签: angulartypescriptionic-frameworkionic2ionic3

解决方案


这是一种在带有接口的打字稿中扩展原型的方法。像这样:

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();

推荐阅读