I have the following CoffeeScript code:
class Person
secret = 0
constructor: (@name, @age, @alive) ->
inc: -> secret++
Which compiles to the following JavaScript code:
var Person;
Person = (function() {
var secret;
secret = 0;
function Person(name, age, alive) {
this.name = name;
this.age = age;
this.alive = alive;
}
Person.prototype.inc = function() {
return secret++;
};
return Person;
})();
Currently secret is shared between all instances of Person. Is there a way to make secret a private instance variable in CoffeeScript?
There is no concept of private members in CoffeeScript as there is none in JavaScript. There are local variables, which you do utilize well in your own solution, but while your solution does hide the
secretvariable from anything outside of aconstructorfunction, it also introduces an overhead of redeclaring theincmethod on every instantiation of a classPerson.A mistake very common in JavaScript community is trying to project inexistent features of other languages on it, which an attempt of mimicing private members is obviously a case of. There’s no such concept in it and thinking deeper you’ll conclude that it would be just unnatural to an extremely loose dynamic environment which JavaScript is.
So don’t waste your time and performance of your application on implementing inexistent constructs. Just concentrate on solving your problem – not the problems of lacking language features.
Now ask yourself: what is so hurtful in having all members public?
Taking everything said into account the ultimate solution would be: