Yad Smood
Yad Smood

Reputation: 2932

Cannot declare named function in coffee-script

If I want to get a function's name by constructor.name.

For example, in js we can do something like this:

var Foo = function Foo() {
    // I need other public methods can also access this private property.
    var non_static_private_member = 10;

    this.a_public_method = function() {
        non_static_private_member = 1;
    }

    console.log(non_static_private_member++);
}
var a = new Foo(); // output >> "10"
var b = new Foo(); // output >> "10"

console.log(a.constructor.name); // output >> "Foo"

But in coffee the b = new Foo can't output 10, it output 11:

class Foo
   non_static_private_member = 10
   constructor: ->
       console.log(non_static_private_member++)

a = new Foo  # output >> "10"
b = new Foo  # output >> "11"
console.log a.constructor.name # output >> "Foo"

But if I declare coffee like this, the output of a.constructor.name is wrong:

Foo = ->
   non_static_private_member = 10
   console.log(non_static_private_member++)

a = new Foo  # output >> "10"
b = new Foo  # output >> "10"
console.log a.constructor.name # output >> ""

How do you translate the js code above to coffee?

Upvotes: 1

Views: 179

Answers (2)

Bergi
Bergi

Reputation: 664256

How do you translate the js code above to coffee?

You put all the code that resides in the constructor function Foo in the constructor of a Foo class:

class Foo
  # what you put here *is* static
  constructor: ->
    # it's an instance member, so it goes into the constructor
    non_static_private_member = 10;

    @a_public_method = ->
      non_static_private_member = 1
      return

    console.log(non_static_private_member++);

a = new Foo(); # output >> "10"
b = new Foo(); # output >> "10"

Upvotes: 2

YellowAfterlife
YellowAfterlife

Reputation: 101

CoffeeScript will only generate named functions when used with class syntax. Basically, your first snippet will translate into

var Foo;
Foo = (function() {
    var non_static_private_member;
    non_static_private_member = 10;
    function Foo() {
        console.log(non_static_private_member++);
    }
return Foo;
})();

while second will become

var Foo;
Foo = function() {
    var non_static_private_member;
    non_static_private_member = 10;
    return console.log(non_static_private_member++);
};

This answer explains the reasoning behind such code generation a bit.

For private fields, you can do a trick similar to JS:

class Foo
   constructor: ->
       non_static_private_member = 10
       console.log(non_static_private_member++)
       @some = -> console.log(non_static_private_member)

a = new Foo  # output >> "10"
b = new Foo  # output >> "10"
a.some() # output >> "11"
console.log a.constructor.name # output >> "Foo"

Upvotes: 0

Related Questions