繁体   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