How to make method private and inherit it in Coffeescript?

柔情痞子 提交于 2020-01-19 17:18:21

问题


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/


回答1:


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/



来源:https://stackoverflow.com/questions/10612293/how-to-make-method-private-and-inherit-it-in-coffeescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!