Skip to content Skip to sidebar Skip to footer

Coffeescript: How To Return A Array From Class?

What is wrong in this class in CoffeeScript ?? @module 'Euclidean2D', -> class @Point constructor: (x,y) -> return if Float32Array? then Float32Array([ x, y ]) e

Solution 1:

You should use new to instantiate the object:

p = new Euclidean2D.Point(1.0,2.0)

If you want to return an Array from the constructor, do it explicitly:

constructor: (x,y) -> 
  returnifFloat32Array? then Float32Array([x,y]) elseArray(x,y)

(By default, Coffeescript doesn't return values from the constructor, so you have to do it explicitly.)


You could have done that, too:

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

Solution 2:

You are defining a constructor but expecting that it behaves like a function. The constructor, however, just sets values in the object to be returned. Since your constructor does not set any attributes in the initializing object, it really does not useful.

You have some alternatives:

  1. Initialize the class as @amaud sugested.

  2. Returns the value from the constructor as @amaud sugested (which does not make much sense to me. This is not the function of a constructor as I feel it. In this case the solution #3 seems better).

  3. define a function instead of a class. IMHO, is the most simple and functional solution

    @Point = (x, y) ->
        ifFloat32Array? then Float32Array([x,y]) elseArray(x,y)
    
  4. If you want Point to be either a specialization of Float32Array or Array, use the option #1 but make Point to inherit from the class you want:

    superclass = ifFloat32Array? then Float32ArrayelseArrayclass@Pointextendssuperclassconstructor: (x,y) ->
        @[0] = x
        @[1] = y
    

EDIT: @amaud676875 posted an interesting question as a comment. Since a reasonable answer would involve some code, I am posting the answer as a edit.

@amaud, for verifying your point, I wrote the following CoffeeScript module:

classFloat32ArrayextendsArray
  first: -> # Just for testing
    @[0]


superclass = if Float32Array? then Float32Array else Array

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

Then I imported the module in the console:

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

and created a Point:

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

This Point has the first() method from Float32Array:

 coffee> p.first()
 3

and instanceof says it is an instance of Float32Array, too:

coffee> p instanceof point.Float32Array
true

So I bet new Point x, y returns an instance of Float32Array. Of course it is an instance of Point, too, and it is not a problem because Pointis-aFloat32Array, to use a classical OOP expression.

Post a Comment for "Coffeescript: How To Return A Array From Class?"