我来自使用基于类的 OO 系统的 C#/Java 背景,但我还没有获得 JavaScript/CoffeeScript 原型 OO 系统。我在下面编写了一个 CoffeeScript 类,它允许我根据系统端的偏好显示联系人的姓名。我只能通过使该joinNonEmpty(stringList, joinText)
方法属于原型并以我在 Java/C# 领域中调用静态方法的方式调用它来使该类工作。
- 有没有办法可以使用这个方法调用
this.joinNonEmpty(...)
? - 你能解释一下为什么我可以
firstLastRender, lastFirstRender and firstOrNickThenLast
用这个来引用构造函数中的方法吗?joinNonEmpty
但是在调用助手时这些方法不起作用? - 这与我如何通过首选项映射找到适当的方法有关吗?
prefs = displayNameFormat: "FirstOrNickThenLast"
class DisplayNameRenderer
constructor: ->
@prefToRenderMap =
FirstLast: this.firstLastRender
LastFirst: this.lastFirstRender
FirstOrNickThenLast: this.firstOrNickThenLast
# Why does this method have to be static (a class method)?
@joinNonEmpty: (stringList, joinText) ->
nonEmptyStrings = []
for s in stringList
nonEmptyStrings.push(s) if s isnt null and s isnt ""
nonEmptyStrings.join(joinText)
firstLastRender: (contact) ->
# TypeError: Object expected.
joinNonEmpty([contact.firstName, contact.lastName], ' ')
lastFirstRender: (contact) ->
# TypeError: Object doesn't support this method or property
this.joinNonEmpty([contact.lastName, contact.firstName], ', ')
firstOrNickThenLast: (contact) ->
# Works correctly.
DisplayNameRenderer.joinNonEmpty([(if contact.nickname isnt null and contact.nickname isnt "" then contact.nickname else contact.firstName), contact.lastName], ' ')
render: (contact) ->
@prefToRenderMap[prefs.displayNameFormat](contact)
contact = firstName: "Jonathan", nickname: "Jonny", lastName: "Appleseed"
dnr = new DisplayNameRenderer()
# => "Jonny Appleseed"
console.log dnr.render(contact)
感谢您花时间回答。