我正在学习如何用JavaScript制作面向对象编程。是否有接口概念(如Java的接口)?
这样我就可以创建一个监听器。
我正在学习如何用JavaScript制作面向对象编程。是否有接口概念(如Java的接口)?
这样我就可以创建一个监听器。
当前回答
这是一个老问题,但这个话题一直困扰着我。
由于这里和网络上的许多答案都专注于“强制”界面,我想提出另一种观点:
当我使用行为相似的多个类(即实现一个接口)时,我感到最缺乏接口。
例如,我有一个电子邮件生成器,期望接收电子邮件节工厂,“知道”如何生成节的内容和HTML。因此,它们都需要某种类型的getContent(id)和getHtml(content)方法。
我能想到的最接近接口的模式(尽管它仍然是一种变通方法)是使用一个将获得2个参数的类,它将定义2个接口方法。
这种模式的主要挑战是,方法要么必须是静态的,要么必须获取实例本身作为参数,以便访问其属性。然而,在有些情况下,我发现这种权衡是值得的。
class Filterable { constructor(data, { filter, toString }) { this.data = data; this.filter = filter; this.toString = toString; // You can also enforce here an Iterable interface, for example, // which feels much more natural than having an external check } } const evenNumbersList = new Filterable( [1, 2, 3, 4, 5, 6], { filter: (lst) => { const evenElements = lst.data.filter(x => x % 2 === 0); lst.data = evenElements; }, toString: lst => `< ${lst.data.toString()} >`, } ); console.log('The whole list: ', evenNumbersList.toString(evenNumbersList)); evenNumbersList.filter(evenNumbersList); console.log('The filtered list: ', evenNumbersList.toString(evenNumbersList));
其他回答
没有“这个类必须有这些函数”的概念(也就是说,本身没有接口),因为:
JavaScript继承基于对象,而不是类。这没什么大不了的,直到你意识到: JavaScript是一种非常动态类型的语言——您可以使用适当的方法创建一个对象,这将使它符合接口,然后取消定义所有使它符合接口的东西。颠覆类型系统是如此容易——甚至是意外地!一开始就尝试创建一个类型系统是不值得的。
相反,JavaScript使用所谓的鸭子类型。(如果它像鸭子一样走路,像鸭子一样嘎嘎叫,在JS看来,它就是一只鸭子。)如果您的对象具有quack()、walk()和fly()方法,那么代码可以在任何期望对象能够walk、quack和fly的地方使用它,而不需要实现某种“Duckable”接口。接口正是代码使用的函数集(以及这些函数的返回值),通过duck键入,您可以免费获得这些功能。
Now, that's not to say your code won't fail halfway through, if you try to call some_dog.quack(); you'll get a TypeError. Frankly, if you're telling dogs to quack, you have slightly bigger problems; duck typing works best when you keep all your ducks in a row, so to speak, and aren't letting dogs and ducks mingle together unless you're treating them as generic animals. In other words, even though the interface is fluid, it's still there; it's often an error to pass a dog to code that expects it to quack and fly in the first place.
但是,如果您确信您所做的事情是正确的,那么您可以在尝试使用特定方法之前通过测试它的存在来解决嘎嘎狗问题。类似的
if (typeof(someObject.quack) == "function")
{
// This thing can quack
}
所以你可以在使用之前检查所有你能用的方法。不过,语法有点难看。有一种稍微漂亮一点的方法:
Object.prototype.can = function(methodName)
{
return ((typeof this[methodName]) == "function");
};
if (someObject.can("quack"))
{
someObject.quack();
}
这是标准的JavaScript,所以它应该适用于任何值得使用的JS解释器。它还有像英语一样阅读的额外好处。
对于现代浏览器(也就是说,除了IE 6-8之外的任何浏览器),甚至有一种方法可以防止该属性在For…in中显示:
Object.defineProperty(Object.prototype, 'can', {
enumerable: false,
value: function(method) {
return (typeof this[method] === 'function');
}
}
问题是IE7对象根本没有. defineproperty,而在IE8中,它据称只作用于宿主对象(即DOM元素等)。如果兼容性是个问题,就不能使用. defineproperty。(我甚至不会提到IE6,因为它在中国以外的地方已经无关紧要了。)
另一个问题是,一些编码风格喜欢假设每个人都写不好的代码,并禁止修改Object。原型,以防有人盲目地使用for…in。如果你关心这个,或者正在使用(IMO坏了)的代码,尝试一个稍微不同的版本:
function can(obj, methodName)
{
return ((typeof obj[methodName]) == "function");
}
if (can(someObject, "quack"))
{
someObject.quack();
}
Javascript没有接口。但它可以是鸭子类型的,一个例子可以在这里找到:
http://reinsbrain.blogspot.com/2008/10/interface-in-javascript.html
像这样的抽象接口
const MyInterface = {
serialize: () => {throw "must implement serialize for MyInterface types"},
print: () => console.log(this.serialize())
}
创建一个实例:
function MyType() {
this.serialize = () => "serialized "
}
MyType.prototype = MyInterface
并使用它
let x = new MyType()
x.print()
这是一个老问题,但这个话题一直困扰着我。
由于这里和网络上的许多答案都专注于“强制”界面,我想提出另一种观点:
当我使用行为相似的多个类(即实现一个接口)时,我感到最缺乏接口。
例如,我有一个电子邮件生成器,期望接收电子邮件节工厂,“知道”如何生成节的内容和HTML。因此,它们都需要某种类型的getContent(id)和getHtml(content)方法。
我能想到的最接近接口的模式(尽管它仍然是一种变通方法)是使用一个将获得2个参数的类,它将定义2个接口方法。
这种模式的主要挑战是,方法要么必须是静态的,要么必须获取实例本身作为参数,以便访问其属性。然而,在有些情况下,我发现这种权衡是值得的。
class Filterable { constructor(data, { filter, toString }) { this.data = data; this.filter = filter; this.toString = toString; // You can also enforce here an Iterable interface, for example, // which feels much more natural than having an external check } } const evenNumbersList = new Filterable( [1, 2, 3, 4, 5, 6], { filter: (lst) => { const evenElements = lst.data.filter(x => x % 2 === 0); lst.data = evenElements; }, toString: lst => `< ${lst.data.toString()} >`, } ); console.log('The whole list: ', evenNumbersList.toString(evenNumbersList)); evenNumbersList.filter(evenNumbersList); console.log('The filtered list: ', evenNumbersList.toString(evenNumbersList));
在Java中需要接口,因为它是静态类型的,并且在编译期间应该知道类之间的契约。在JavaScript中则不同。JavaScript是动态类型的;这意味着当你获得对象时,你可以检查它是否有特定的方法并调用它。