【问题标题】:Implement object.prototype.function in ionic 3在 ionic 3 中实现 object.prototype.function
【发布时间】:2020-03-04 18:15:12
【问题描述】:

我在下面的 Javascript 代码中创建了一个对象作为 new Box2 并将每个对象插入到一个数组中。内部循环我在每个元素上调用 draw()。在普通 js 中一切正常,但我想在 ionic 3 中实现此代码。如果将相同的代码复制到 Ionic 的 .ts 文件中,在编辑器中它会给出 error as
[ts] 重复标识符“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");
    }
  }

【问题讨论】:

    标签: angular typescript ionic-framework ionic2 ionic3


    【解决方案1】:

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

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

    【讨论】:

    • 感谢您的回复。我通过使用 Box2 类创建另一个文件并在该类中实现 draw() 来实现此功能。我已将文件导入到我想使用它的位置并创建了 Box2 对象。
    • 不客气。随时通过编辑您的帖子来分享您的解决方案(如果有帮助,请点赞我的帖子;))
    猜你喜欢
    • 1970-01-01
    • 2018-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-27
    • 1970-01-01
    • 2018-11-08
    • 1970-01-01
    相关资源
    最近更新 更多