簡體   English   中英

coffeescript類中是否可以具有相同名稱的靜態函數和成員函數?

[英]Is it possible to have a static function and member function of the same name in a coffeescript class?

如果我對問題的措詞不正確,或者很難理解我要問的內容,那么這是我要執行的操作的簡化示例。

class Number
  constructor: (@num) ->

  @add: (operand1, operand2) ->
    return operand1 + operand2

  add: (operand) =>
    @num = @add(@num, operand)

Number num1
Number num2
Number.add(num1, num2)
num1.add(num2)

這樣做的目的是使Number.add(num1, num2)可以靜態使用,以返回Number類的兩個對象的和,以便Number類的對象可以使用num1.add(num2)添加另一個使用靜態函數的代碼為其編號對象。 當我嘗試在項目中實現類似的代碼時,結果是遞歸的混亂。 我意識到在add函數中調用@add就是在調用自身,這不是這里想要的。 我正在嘗試做的事情甚至是可能的嗎?

num1num2是對象,您必須使用它們的num屬性:

class Number
  constructor: (@num) ->

  @add: (operand1, operand2) ->
    # the addition must be done on num property
    operand1.num + operand2.num

  add: (operand) ->
    # here, you must call Number.add
    Number.add(@, operand)

# to create Number, use new Number
num1 = new Number 10
num2 = new Number 5
console.log Number.add(num1, num2)
console.log num1.add(num2)

在兩個add()函數中,都應檢查操作數是否為Number以避免發生任何錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM