在这些替代方案中,哪一种是CoffeeScript中基于类的编程的最佳样式?
# Alternative 1
class Person
constructor: (@name, @age) ->
new Person "Peter", 19
# Alternative 2
class Person
name: ""
age: 0
constructor: (@name, @age) ->
new Person "Peter", 19
# Alternative 3
class Person
constructor: (@name = "", @age = 0) ->
new Person "Peter", 19
# Alternative 4
class Person
constructor: (name, age) ->
@name = name ? ""
@age = age ? 0
new Person "Peter", 19
解决方法:
嗯#1很简单. #3简洁地显示了预期的参数格式(尽管默认值实际上没有意义-除非您期望一个人被命名为“”或0岁).
我真的建议使用哈希代替:
class Person
constructor: ({@name, @age}) ->
new Person(name: "Peter", age: 19)
这使您不必记住参数的顺序,并使您的实例化调用更加自我记录.
(我在CoffeeScript: Accelerated JavaScript Development中的某些示例中使用了这种方法.)