Private and public variables or methods in classes #222

Closed
rainerborene opened this Issue Feb 28, 2010 · 4 comments

Comments

Projects
None yet
4 participants

It would be great to have private and public variables in classes. Any possibility for that? I have no idea on how this could be implemented on JavaScript... But in CoffeScript I'm thinking of something like this:

class Person
  constructor: (name) ->
    @name: name

  say: (something) ->
    alert something

  sayHello:
    @say "Hello World"

  private :say
Contributor

StanAngeloff commented Feb 28, 2010

It would be difficult to get private members in Coffee since JavaScript does not provide a true OOP model to base these on. I was thinking about using closures to achieve something similar:

class A
    internal write: ->
        puts arguments...

    say: ->
        write 'Hello!'

(note the internal before write)

var A;
(function() {
var write;
A = function A() {};
write = function write() {
  return puts.apply(this, arguments);
};
A.prototype.say = function say() {
  return write('Hello!');
};
})();

This way write is only accessible within class A, though you have to manually apply if you want to get this bound correctly. Too much hassle for my liking.

Owner

jashkenas commented Feb 28, 2010

Yep, there's no way to attach a function directly to the prototype, while having it remain private. For many people, the convention is simply to prefix "private" methods in JavaScript with "_", so that you know not to use them from outside of the class.

If you need a truly private method, define a helper function above the class definition, without exporting it. It'll be visible to all of the class' methods through the closure, and invisible to other classes outside of the file. i.e:

seppuku: (samurai) ->
  samurai.stomach.disembowel()

class Samurai
  fight: (opponent) ->
    if opponent.honor > this.honor
      seppuku this

Closing as a 'wontfix'.

Contributor

StanAngeloff commented Feb 28, 2010

I reckon Jeremy's examples are getting more creative by the day !

firedev commented Nov 2, 2015

It would be nice to simply allow word private to be inserted in code for easier reading. I know I can add comment, that's what I do. But it would read really nice if I could mark the rest of the file as private

This issue was closed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment