Javascript 如何实现接口?
最近在学习 JS 的面向对象实现,看「Javascript 设计模式」看不明白 JS 关于接口是怎么实现的。
比如有一个方法是这样的:
var say = function(){
alert("Hello");
}
有三个类,分别是 People、Dog、Alien,其中 People 和 Alien 都可以 say()
,那么如何用 JS 去实现这个接口呢?
Ps:也不知道我对于「接口」的理解是否正确,我的理解是多个类同时都会用到的公共方法,如有错误请指正……
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
下面有一段在JS中使用接口的代码,不知道是不是你在《JavaScript设计模式》中看到的,该段代码模拟了接口,支持多个接口的情况。
摘自
使用方法
Demo
接口是由於靜態語言的緣故才需要的。比如只有 sayable 的,纔可以調用 say,這在編譯時就可以檢查。
而 js 是動態語言。
其實你在 js 中完全可以拋棄傳統面向對象語言當中的詞彙和思路。
面向對象可以不需要類,不需要接口,不需要繼承。。。
面向對象只是一種對事物本質的抽象。
而 js 實現這種抽象使用的語言,叫做原型。
你这个不叫接口,接口是实现声明和约束
你这个更靠近继承和多态