Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Need help understanding class member meanings #5453

Open
rayzorben opened this issue Sep 10, 2023 · 1 comment
Open

Need help understanding class member meanings #5453

rayzorben opened this issue Sep 10, 2023 · 1 comment

Comments

@rayzorben
Copy link

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

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

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
@Inve1951
Copy link
Contributor

class Test
  @foo = "foo" # static member (shorthand for `Test.foo = "foo"`)
  bar = "bar" # class-scoped variable (behaves like a private static)
  baz: "baz" # instance member

With : in a class body you assign a prototype property. This is only done once.
Unless the value is a primitive, all class instances inherit the same object reference, which causes the behavior you see.

Default values for non-primitives should be assigned in the constructor (@member = value).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants