簡體   English   中英

CoffeeScript:如何從類返回數組?

[英]CoffeeScript: How to return a array From class?

CoffeeScript此類中的錯誤是什么?

@module "Euclidean2D", ->
  class @Point
    constructor: (x,y) -> 
      return if Float32Array? then Float32Array([ x, y ]) else Array(x,y)

我希望它表現為:

p = new Point(1.0,2.0);
p[0] == 1.0
p[1] == 2.0

但是用茉莉花測試我得到“期望未定義等於1”。

describe "Point", ->

    beforeEach ->
      @point = new Euclidean2D.Point(1.0,2.0)

    it "extracts values", ->
      (expect @point[0]).toEqual 1.0
      (expect @point[1]).toEqual 2.0

CoffeeScript或Jasmine中是否有錯誤?

而且所有這些都在一個模塊中,例如:

@module = (names, fn) ->
  names = names.split '.' if typeof names is 'string'
  space = @[names.shift()] ||= {}
  space.module ||= @module
  if names.length
    space.module names, fn
  else
    fn.call space

在Chrome控制台中,我得到:

a = new Euclidean2D.Point(1.0,2.0)
-> Point
a[0]
undefined
b = new Float32Array([1.0,2.0])
-> Float32Array
b[0]
1

編輯:再次..對不起

已結合使用@brandizzi和@ arnaud576875答案來解決。 官方CoffeeScript Wiki中規定的@module無效。 結果是:

class @Point
        constructor: (x, y) ->
            return if Float32Array? then Float32Array([ x, y ]) else Array(x,y)

您應該使用new實例化該對象:

p = new Euclidean2D.Point(1.0,2.0)

如果要從構造函數返回Array,請明確進行操作:

constructor: (x,y) -> 
  return if Float32Array? then Float32Array([x,y]) else Array(x,y)

(默認情況下,Coffeescript不會從構造函數中返回值,因此您必須顯式地執行該操作。)


您也可以這樣做:

class @Point
  constructor: (x,y) ->
    @[0] = x
    @[1] = y    

您正在定義一個構造函數,但是期望它的行為像一個函數。 但是,構造函數只在要返回的對象中設置值。 由於構造函數沒有在初始化對象中設置任何屬性,因此它實際上沒有用。

您有一些選擇:

  1. 初始化類為@amaud提示。

  2. 從@amaud sugested中返回構造函數的值(對我而言這沒有多大意義。按照我的感覺,這不是構造函數的功能。在這種情況下,解決方案#3似乎更好)。

  3. 定義一個函數而不是一個類。 恕我直言,是最簡單,最實用的解決方案

     @Point = (x, y) -> if Float32Array? then Float32Array([x,y]) else Array(x,y) 
  4. 如果希望PointFloat32ArrayArray ,請使用選項#1,但要使Point繼承自所需的類:

     superclass = if Float32Array? then Float32Array else Array class @Point extends superclass constructor: (x,y) -> @[0] = x @[1] = y 

編輯 :@ amaud676875發表了一個有趣的問題作為評論。 由於合理的答案將涉及一些代碼,因此我將答案發布為編輯內容。

@amaud,為了驗證您的觀點,我編寫了以下CoffeeScript模塊:

class Float32Array extends Array
  first: -> # Just for testing
    @[0]


superclass = if Float32Array? then Float32Array else Array

class @Point extends superclass
  constructor: (x,y) ->
    @[0] = x
    @[1] = y

然后,我將模塊導入控制台:

coffee> point = require './point'
{ Point: { [Function: Point] __super__: [ constructor: [Object], first: [Function] ] },
 Float32Array: { [Function: Float32Array] __super__: [] } }

並創建一個Point

 coffee> p = new point.Point 3, 2
 [ 3, 2 ]

Point具有Float32Arrayfirst()方法:

 coffee> p.first()
 3

instanceof表示它也是Float32Array的實例:

coffee> p instanceof point.Float32Array
true

所以我押注new Point x, y返回一個Float32Array的實例。 當然,它也是Point的實例,這也不是問題,因為Point Float32Array ,可以使用經典的OOP表達式。

暫無
暫無

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

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