如何使方法私有和继承它在Coffeescript? [英] How to make method private and inherit it in Coffeescript?
问题描述
如何使方法btnClick私有?
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
推荐答案
JavaScript中没有私有,所以CoffeeScript没有私有。你可以在类级别使事情私有,像这样:
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')
private_function
只会在 C
中显示。问题是 private_function
只是一个函数,它不是 C
实例上的方法。您可以使用 Function.apply
或 Function.call
:
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: ', @)
演示:http://jsfiddle.net/ambiguous/5v3sH/
或者,如果您不需要 @ 在
btnClick
可以是任何特别的,你可以只是使用的功能是:
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
演示:http://jsfiddle.net/ambiguous/zGU7H/
这篇关于如何使方法私有和继承它在Coffeescript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!