Reputation: 13221
In JavaScript I'd set up a class like:
var SomeClass = (function()
{
var _this = { };
var privateVar = 'foo'
_this.publicVar = 'bar'
function privateFunction()
{
return privateVar;
}
_this.publicFunction = function()
{
return _this.publicVar;
}
return _this;
})();
This is fine as in privateFunction
I can reference publicFunction
by either calling SomeClass.publicFunction()
or _this.publicFunction()
Now in Coffeescript I'm trying to set up my class so that I can call class functions, how do I go about this? How can I create a class in coffeescript called Foo
and get a function in the class to reference another function in that class?
Upvotes: 1
Views: 280
Reputation: 120178
Your question is confusing.
If you want to create a class method, you could do it like
class Foo
constructor: ->
m1: ->
Foo.classMethod()
m2: ->
@privateMethod()
@m1()
Foo.classMethod = ->
note the last line. A class method is one that lives on the function that defines the class.
If you want to call a method from another method, its no big deal. m1
and m2
in this example demonstrate this. Note that each invocation is scoped to this
, which is the current instance of your class Foo. So you could do
f = new Foo()
f.m2()
which would create a new instance of Foo, and then invoke m2
on that instance. m2
in turn invokes the class method classMethod
.
Check this out to see the javascript to which the above coffeescript compiles.
Upvotes: 1
Reputation: 600
Invoking public method inside a private method
method a is private and method b is public
class Foo call_a: -> a.call(this) b: -> alert 'b invoked' a = -> alert 'a invoked' @b() obj = new Foo obj.call_a()
Upvotes: 0
Reputation: 600
I think this would help :
class Foo
a: ->
alert 'a invoked'
b: ->
@a()
alert 'b invoked'
new Foo().b()
Upvotes: 2