javascript - CoffeeScript:如何从类中返回一个数组?

标签 javascript arrays indexing coffeescript

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

但是用 Jasmine 测试时我得到“Expected undefined to equal 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)

如果你想从构造函数返回一个数组,明确地做:

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

(默认情况下,Coffeescript 不会从构造函数返回值,因此您必须显式返回值。)


你也可以这样做:

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

关于javascript - CoffeeScript:如何从类中返回一个数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7421781/

相关文章:

javascript - Vue.js 显示空白(换行符)

javascript - 背景图像和颜色在 IE 或 Firefox 中不变

Javascript,使用 if 语句更改单击元素的颜色

r - 矩阵 R 中的 [] 运算符

javascript - 如何在函数中引用自身而不考虑外部变量的变化?

javascript - 如何遍历数组并检查数组值

arrays - 有没有更好的方法来可视化数组?

java - 图像图标列表

c - 尝试在 C 中引用值时出现 LValue 错误

mysql - 在mysql中创建索引的不同方法?