问题描述
如何将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
http://jsfiddle.net/R646x/17/
推荐答案
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 中继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!