【问题标题】:Implementing JavaScript Web API Interfaces实现 JavaScript Web API 接口
【发布时间】:2014-03-16 11:45:52
【问题描述】:

HTMLElement(及其后代,如HTMLDivElementHTMLSpanElement 等)根据MDN documentation 定义为接口。

如果我想用 TypeScript 实现这些接口,我可以执行以下操作。

class CustomElement implements HTMLElement {
    // implementation
}

但是在 TypeScript 中实现接口不会生成任何代码,所以很难看出如何用纯 JavaScript 实现接口。

这些接口应该如何用纯 JavaScript 实现?

【问题讨论】:

    标签: javascript interface typescript


    【解决方案1】:

    jsFiddle Demo

    你会使用 HTMLElement 的原型

    var CustomElement = function(){}; 
    CustomElement.prototype = HTMLElement.prototype;
    

    现在您可以使用 new 关键字构造它们

    var myElement = new CustomElement();
    //myElement will now have access to the HTMLElement prototype
    

    【讨论】:

      猜你喜欢
      • 2016-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-09
      • 2021-09-12
      • 1970-01-01
      • 2018-05-25
      • 2012-03-18
      相关资源
      最近更新 更多