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 中继承?


- 如何显示带有换行符的文本标签? 2022-01-01
- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01
- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 为什么我的页面无法在 Github 上加载? 2022-01-01
- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01
- 从原点悬停时触发 translateY() 2022-01-01
- 如何向 ipc 渲染器发送添加回调 2022-01-01
- 在不使用循环的情况下查找数字数组中的一项 2022-01-01