Javascript CoffeeScript:如何从类返回数组?
这节课上的咖啡脚本有什么问题Javascript CoffeeScript:如何从类返回数组?,javascript,arrays,indexing,coffeescript,Javascript,Arrays,Indexing,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测试我得到“预期未定义为等于1”
@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测试我得到“预期未定义为等于1”
咖啡脚本或茉莉花中有错误吗
此外,所有这些都在一个模块中,如:
@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
您正在定义构造函数,但希望它的行为类似于函数。然而,构造函数只是在要返回的对象中设置值。由于构造函数没有在初始化对象中设置任何属性,因此它实际上没有用处 你有一些选择:
@Point = (x, y) ->
if Float32Array? then Float32Array([x,y]) else Array(x,y)
Point
成为Float32Array
或Array
的特化,请使用选项#1,但要使Point
从所需的类继承:
superclass = if Float32Array? then Float32Array else Array
class @Point extends superclass
constructor: (x,y) ->
@[0] = x
@[1] = y
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__: [] } }
并创建了一个点
:
coffee> p = new point.Point 3, 2
[ 3, 2 ]
此点
具有来自Float32Array
的first()
方法:
coffee> p.first()
3
并且instanceof
说它也是Float32Array
的一个实例:
coffee> p instanceof point.Float32Array
true
所以我打赌
newpointx,y
返回Float32Array
的一个实例。当然,它也是点
的一个实例,这也不是问题,因为点
是一个Float32Array
,使用经典的OOP表达式。新的就在那里,抱歉。。但我想创建一个Float32Array,而不仅仅是Array。。如果不支持Float32Array,那么我使用Arraythen在if Float32Array?之前添加一个返回构造函数中的code>(默认情况下,coffeescript不会从构造函数返回值)确定,更改为。。它仍然给出未定义的。。更改了问题以反映它现在是如何工作的;尝试清除缓存/重新编译脚本为什么使用“类欧几里德2D”??在实践中,它是相同的?您确定新点(x,y)
真的返回Float32Array实例吗?似乎不是to@amaud我在我的帖子中回复为编辑。看看它是否能澄清/理解情况。谢谢!它是否也适用于本机Float32Array?(c.f.类Float32Array扩展了Array
)。对我来说,这些类型化数组似乎有点特殊,我不确定您是否会继承这些数组的优点。使用它解决了。。非常感谢,还需要删除@module,使用amaud类Euclidian2D来git一些namespace@arnaud老实说,我以前从未见过这门课。我想用本地的来测试一下。我怎样才能访问它?
coffee> p instanceof point.Float32Array
true