jashkenas / jashkenas/coffeescript

Need help understanding class member meanings

Open
#5,453 1 comment 0 reactions 0 assignees View on GitHub
Dominant language
CoffeeScript
Stars
16.6k
Forks
2k
PR merge metrics
No merged PRs in 30d

Description

I noticed that you can put class members outside of the constructor in a class such as

```coffeescript
class Test
@foo = "foo" # static variable
bar = "bar" # private variable
baz: "baz" # instance variable accessible by @baz
```

The last one, the 'instance variable' seems to work, but has unexpected behavior when it comes to arrays. Other values are re-initialized across instantiations, but array variables are not

```coffeescript
class Test
here: []
test: 0

constructor: (value, value2) ->
@here.push value
console.log @here
console.log @test
@test = value2
console.log @test

testa = new Test 'a', 1
testb = new Test 'b', 2
```

As you can see here, `test` always starts out at 0, but `here` doesn't get re-initialized and will keep getting new values pushed onto the old array, which I find odd.

Output:
```
[ 'a' ]
0
1
[ 'a', 'b' ]
0
2
```

Contributor guide

Open the contributing guide

Research direction

The issue provides a CoffeeScript class example but names no source file or test. Start by reproducing the example and inspecting the generated JavaScript for the scalar and array members. A complete resolution would need to establish whether the behavior is intended and, if not, define the expected initialization semantics.

Written by the indexing model from the issue text.

Assessment

Tech stack
coffeescript
Domain
compilers
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
20/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.