实现JavaScript Web API接口

时间:2014-02-17 09:02:44

标签: javascript interface typescript

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

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

class CustomElement implements HTMLElement {
    // implementation
}

然而,在TypeScript中实现接口不会生成任何代码,因此很难看到如何使用纯JavaScript实现接口实现。

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

1 个答案:

答案 0 :(得分:3)

jsFiddle Demo

您将使用HTMLElement的原型

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

现在,您可以使用new关键字

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