Encapsulation in Coffee Script

m.coffee
---------
publicMethod1 = ->
  @publicMember1 = "public member 1"
  @publicMember2 = "public member 2"
  console.log 'publicMethod1***'
  console.log '*' + @publicMember1

publicMethod2 = ->
  console.log 'publicMethod2***'
  @publicMethod1()
  console.log '*' + @publicMember2

class Foo
  constructor: ->
    @fooPublicMember1 = "Foo public member 1"
    @fooPublicMember2 = "Foo public member 2"
    privateMember1 = "private member 1"
    privateMember2 = "private member 2"

    privateMethod = ->
      console.log 'FooPrivateMethod***'
      console.log '*' + privateMember1

    @privilegedMethod = ->
      console.log 'FooPrivilegedMethod***'
      privateMethod()
      console.log '*' + module.exports.publicMember1
      console.log '*' + @fooPublicMember1
      console.log '*' + privateMember2

  publicMethod: ->
    console.log 'FooPublicMethod***'
    console.log '*' + module.exports.publicMember2
    console.log '*' + @fooPublicMember2
    @privilegedMethod()

module.exports =
  publicMethod1: publicMethod1
  publicMethod2: publicMethod2
  Foo: Foo

c.coffee
--------
m = require './m'

m.publicMethod1()
m.publicMethod2()
console.log m.publicMember1

foo = new m.Foo
foo.privilegedMethod()
foo.publicMethod()
console.log foo.fooPublicMember1

results
--------
publicMethod1***
*public member 1
publicMethod2***
publicMethod1***
*public member 1
*public member 2
public member 1
FooPrivilegedMethod***
FooPrivateMethod***
*private member 1
*public member 1
*Foo public member 1
*private member 2
FooPublicMethod***
*public member 2
*Foo public member 2
FooPrivilegedMethod***
FooPrivateMethod***
*private member 1
*public member 1
*Foo public member 1
*private member 2
Foo public member 1

About rp8

Specialized in building sophisticated systems for trading & risks in commodity, exotics, commodity index & structured products. Specially interested in using open source stacks and cloud computing to build new generation of services and apps. Enjoy mountain biking & photography. github
This entry was posted in Node.js and tagged . Bookmark the permalink.