Public class members in coffeescript
I am very new to coffeescript, and I have been trying to find a way to make publicly accessible class members. If I run the following code:
class cow
n = 7
moo: ->
alert("moo")
bessie = new cow
alert(bessie.n);
It will show that bessie.n
is undefined. Th开发者_如何学Goe only solution I can find is to make getters and setters like n: -> n
and setN: (value) -> n = value
. I then must use function calls instead of simple property accesses. This feels cumbersome for a language which sells itself based on syntactic sugar.
Is there something I missed in the documentation that makes it easier to make classes with simple public members? What is the best practice for this?
It's no different from setting methods.
Just try this
class cow
n: 7
Doing only
class cow
n = 7
Will just set private variable inside the class closure.
Use try coffeescript link on http://coffeescript.org/ to see what it compiles to.
when you need a private member, you typically can't use a private static member in its place.
The concept of private variables is easily implemented via Crockfords suggestions, but this isn't a proper CoffeeScript class and as such you can't extend it. The winner is that you get an object with methods where no one else can read/write your variable making it a little more foolproof. Note you don't use the 'new' keyword (which Crockford considers a bad practice anyway)
Counter = (count, name) ->
count += 1
return {
incr : ->
count = count + 1
getCount : ->
count
}
c1 = Counter 0, "foo"
c2 = Counter 0, "bar"
c3 = Counter 0, "baz"
console.log c1.getCount() # return 1 regardless of instantiation number
console.log c1.count # will return undefined
精彩评论