JavaScript中的接口是否必要? [英] Are Interfaces in JavaScript necessary?

查看:103
本文介绍了JavaScript中的接口是否必要?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想这可能适用于任何动态语言,但我使用的是JavaScript。我们有一种情况,我们在JavaScript中编写了一些需要公开Send()函数的控件,然后由承载JavaScript的页面调用该函数。我们有一个定义了这个Send函数的对象数组,所以我们遍历集合并在每个对象上调用Send()。

I suppose this could apply to any dynamic language, but the one I'm using is JavaScript. We have a situation where we're writing a couple of controls in JavaScript that need to expose a Send() function which is then called by the page that hosts the JavaScript. We have an array of objects that have this Send function defined so we iterate through the collection and call Send() on each of the objects.

在OO语言中,如果你想做类似的事情,你有一个IControl接口,它有一个必须由每个控件实现的Send()函数,然后你有一个IControl实现的集合,你要迭代并调用send方法on。

In an OO language, if you wanted to do something similar, you'd have an IControl interface that has a Send() function that must be implemented by each control and then you'd have a collection of IControl implementations that you'd iterate through and call the send method on.

我的问题是,JavaScript是一种动态语言,是否需要定义控件应该继承的接口,或者它是否足够好调用控件上公开的Send()函数?

My question is, with JavaScript being a dynamic language, is there any need to define an interface that the controls should inherit from, or is it good enough to just call the Send() function exposed on the controls?

推荐答案

动态语言经常鼓励 Duck Typing ,其中对象的方法决定了它应该如何使用而不是明确的契约(例如界面)。

Dynamic languages often encourage Duck Typing, in which methods of the object dictate how it should be used rather than an explicit contract (such as an interface).

这篇关于JavaScript中的接口是否必要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆