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/