How to make method private and inherit it in Coffeescript?(如何将方法设为私有并在 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
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 中继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将方法设为私有并在 Coffeescript 中继承?


基础教程推荐
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 在for循环中使用setTimeout 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 动态更新多个选择框 2022-01-01