CoffeeScript非常棒,它的类系统实际上是所有javascript所需要的,几个关键字,到处都是更少的proto*和花括号。我见过人们在类中实现混入,但我想知道是否有实现Java接口类比的途径?
如果不是,这可能是一个很好的补充..毕竟,如果知道我的代码在编译时是否可以像鸭子一样成功地行走/叫,那将是一件很好的事情。下面的说明可能会更好地帮助什么将是理想的…现在你可以通过创建单元测试来解决这个问题(无论如何你都应该这样做),所以这不是什么大问题,但仍然会很好。
class definitiona
class definitionb
class featurex
class featurey
class childa extends definitiona implements featurex
class childb extends definitionb implements featurex, featurey发布于 2011-11-30 06:10:57
通常,JavaScripters会拒绝类似Java主义的接口。毕竟,接口的用处在于它们检查对象在编译时是否“像鸭子一样嘎嘎叫”,而JavaScript不是一种编译语言。CoffeeScript是,但是像强制接口这样的事情远远超出了它的范围。像Dart这样更严格的编译到JS语言可能更适合您。
另一方面,如果您想将featurex和featurey作为混合使用,这在CoffeeScript-land中是很常见和容易做到的。您可能想看看CoffeeScript小手册中的classes chapter,它展示了实现这一点是多么容易:只需将featurex定义为一个对象,您可以将其方法添加到childa的原型中。
发布于 2015-11-17 06:18:59
我知道我来晚了。我不会争论为什么/为什么不这样做的优点,因为它只是您开发人员工具箱中的一个工具,但我是这样做的:
class.coffee
# ref - http://arcturo.github.io/library/coffeescript/03_classes.html#extending_classes
# ref - http://coffeescriptandnodejs.blogspot.com/2012/09/interfaces-nested-classes-and.html
#
# @nodoc
#
classKeywords = ['extended', 'included', 'implements', 'constructor']
#
# All framework classes should inherit from Class
#
class Class
#
# Utility method for implementing one of more mixin classes.
#
# @param objs [Splat] One or more mixin classes this class will *implement*.
#
@implements: (objs...) ->
for obj in objs
if typeof obj is 'function' and Boolean(obj.name)
obj = obj.prototype
for key, value of obj #when key not in moduleKeywords
# Assign properties to the prototype
if key not in classKeywords
#console.log 'implementing', value.toString(), 'as', key
@::[key] = value
obj.included?.apply(@)
this
#
# Utility method for adding getter/setters on the Class instance
#
# @param prop [String] The name of the getter/setter.
# @param desc [Object] The object with a getter &/or setter methods defined.
#
@property: (prop, desc)-> Object.defineProperty @prototype, prop, descinterface.quack.coffee
class iQuack
quack: -> throw new Error 'must implement interface method'duck.coffee
class Duck extends Class
@implements iQuack
quack: -> console.log 'quack, quack'发布于 2012-09-11 17:56:13
我也有同样的问题,我试图通过在Function中添加includes方法来解决这个问题。我把它描述为here。这个解决方案允许实现多个接口,并为Object原型提供了额外的方法,可以用来代替instanceof操作符(因为我们不能覆盖任何JavaScript操作符)。
https://stackoverflow.com/questions/8315828
复制相似问题