哪种风格最适合 CoffeeScript 中基于类的编程?

发布于 2024-12-17 13:11:43 字数 497 浏览 5 评论 0原文

在这些替代方案中,哪一种是 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

北风几吹夏 2024-12-24 13:11:43

唔。 #1 很好而且简单。 #3 简洁地显示了参数的预期格式(尽管默认值实际上没有意义 - 除非您期望一个人被命名为 ""0代码>岁)。

我真正建议的是使用哈希来代替:

class Person
  constructor: ({@name, @age}) ->

new Person(name: "Peter", age: 19)

这使您不必记住参数的顺序,并使您的实例化调用更加自记录。

(我在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 be 0 years old).

What I'd really recommend is using a hash instead:

class Person
  constructor: ({@name, @age}) ->

new Person(name: "Peter", age: 19)

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.)

亣腦蒛氧 2024-12-24 13:11:43

#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.

瀞厅☆埖开 2024-12-24 13:11:43

第一种方式更清晰。我总是使用这种方法。

First way is more clear. I always use this approach.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文