Cor*_*ore 8 inheritance interface coffeescript
CoffeeScript非常棒,类系统真的是所有需要的javascript,一些关键字和更少的proto*和大括号无处不在.我见过人们在类中实现mixins,但我想知道是否有实现类似于Java接口的路径?
如果不是它可能是一个很好的补充..毕竟,我很高兴知道我的代码是否可以在编译时成功地行走/嘎嘎作为鸭子.以下说明可能会更好地帮助理想的东西...现在你可以通过创建单元测试来解决它(你应该做什么)所以它不是那么大,但仍然会很好.
class definitiona
class definitionb
class featurex
class featurey
class childa extends definitiona implements featurex
class childb extends definitionb implements featurex, featurey
Run Code Online (Sandbox Code Playgroud)
通常,JavaScripters拒绝接口等Java-isms.毕竟,接口的用处是它们在编译时检查对象是否"像鸭子一样嘎嘎叫",而JavaScript不是编译语言.CoffeeScript是,但强制接口之类的东西远远超出了它的范围.像Dart这样更严格的编译到JS的语言可能更像是你的胡同.
另一方面,如果你想做featurex
和featurey
作为mixins,那就是在CoffeeScript-land中相当普遍和容易做的事情.你可能想看看班章中关于CoffeeScript的小书,这说明它是多么容易做到这一点:只要定义featurex
为一个对象,其方法你加入的原型childa
.
我知道我迟到了.我不会争论为什么/为什么不这样做的优点,因为它只是开发人员工具箱中的一个工具,但这就是我这样做的方式:
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, desc
Run Code Online (Sandbox Code Playgroud)
interface.quack.coffee
class iQuack
quack: -> throw new Error 'must implement interface method'
Run Code Online (Sandbox Code Playgroud)
duck.coffee
class Duck extends Class
@implements iQuack
quack: -> console.log 'quack, quack'
Run Code Online (Sandbox Code Playgroud)
https://gist.github.com/jusopi/3387db0dd25cd11d91ae
归档时间: |
|
查看次数: |
4449 次 |
最近记录: |