container=(param) ->
@member=param# Private memberssecret=3that=this# By convention, we make a private that variable. # This is used to make the object available to the private methods.# This is a workaround for an error in the ECMAScript Language Specification which # causes this to be set incorrectly for inner functions.# private method dec=->ifsecret > 0secret -= 1trueelsefalse# privileged method@service=->ifdec()then@memberelsesecretthatc=container("abc")alertc.service()# => "abc"alertc.service()# => "abc"alertc.service()# => "abc"alertc.service()# => 0alertc.dec()# => exception, TYpeError: No method dec()# public methodc.adam=->#dec() # => ReferenceError: dec is not defined#secret # => ReferenceError: secret is not defined@memberalertc.adam()# => "abc"alertc.adam()# => "abc"
Code example 2 (Functional - JavasScript the Good parts)
# spec - The contents of the spec could be copied into private variables# or transformed by other functions.# my - The my object is a container of secrets that are shared by the # constructors in the inheritance chain.cat=(spec,my) ->
that={}secret=1my=my || {}# private methods dec=->ifsecret > 0secret -= 1trueelsefalseservice=->ifdec()thenspec.nameelsesecret# Privileged method (public)that.service=servicereturnthatc=cat({name: "abc"})alertc.service()# => "abc"alertc.service()# => 0#alert c.dec() # => exception, TYpeError: No method dec()