1

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?

0

3 Answers 3

2

I think this would help :


class Foo
  a: ->
    alert 'a invoked'
  b: ->
    @a()
    alert 'b invoked'
new Foo().b()

Sign up to request clarification or add additional context in comments.

1 Comment

So how about 'private' functions?
1

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.

4 Comments

So how about 'private' functions?
updated -- you do it in your constructor. Check out the link at the bottom so you can see the js
@AhmedNuaman, see stackoverflow.com/questions/10612293/… re private
@AhmedNuaman: This one might also be helpful: stackoverflow.com/q/9347782/479863
0

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.