Search code examples
javascriptcoffeescriptprivate-members

How to make method private and inherit it in Coffeescript?


How to make method "btnClick" private?

class FirstClass
  constructor: ->
    $('.btn').click @btnClick

  btnClick: =>
    alert('Hi from the first class!')

class SecondClass extends FirstClass
  btnClick: =>
    super()
    alert('Hi from the second class!')

@obj = new SecondClass

http://jsfiddle.net/R646x/17/


Solution

  • There's no private in JavaScript so there's no private in CoffeeScript, sort of. You can make things private at the class level like this:

    class C
        private_function = -> console.log('pancakes')
    

    That private_function will only be visible within C. The problem is that private_function is just a function, it isn't a method on instances of C. You can work around that by using Function.apply or Function.call:

    class C
        private_function = -> console.log('pancakes')
        m: ->
            private_function.call(@)
    

    So in your case, you could do something like this:

    class FirstClass
        btnClick = -> console.log('FirstClass: ', @)
        constructor: ->
            $('.btn').click => btnClick.call(@)
    
    class SecondClass extends FirstClass
        btnClick = -> console.log('SecondClass: ', @)
    

    Demo: http://jsfiddle.net/ambiguous/5v3sH/

    Or, if you don't need @ in btnClick to be anything in particular, you can just use the function as-is:

    class FirstClass
        btnClick = -> console.log('FirstClass')
        constructor: ->
            $('.btn').click btnClick
    

    Demo: http://jsfiddle.net/ambiguous/zGU7H/