哪种风格最适合 CoffeeScript 中基于类的编程?
在这些替代方案中,哪一种是 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
Of these alternatives, which is the best style for class-based programming in 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
唔。 #1 很好而且简单。 #3 简洁地显示了参数的预期格式(尽管默认值实际上没有意义 - 除非您期望一个人被命名为
""
或0
代码>岁)。我真正建议的是使用哈希来代替:
这使您不必记住参数的顺序,并使您的实例化调用更加自记录。
(我在CoffeeScript:加速 JavaScript 开发中的一些示例中使用了这种方法。)
Hmm. #1 is nice and simple. #3 succinctly shows the expected format of the arguments (though the defaults don't actually make sense—unless you're expecting a person to be named
""
, or to be0
years old).What I'd really recommend is using a hash instead:
This frees you from having to memorize the order of the arguments, and makes your instantiation calls more self-documenting.
(I use this approach in some of the examples in CoffeeScript: Accelerated JavaScript Development.)
#1 可以,但不要确定默认值。
#2 和 #3 是等价的,如果班级不大,我会使用 #3。
我认为#4 过于复杂。
The #1 is ok, but don't determine default values.
#2 and #3 are equivalents, if the class isn't big I would use the #3.
I think #4 is unnecessarily complex.
第一种方式更清晰。我总是使用这种方法。
First way is more clear. I always use this approach.