无法在coffee-script中声明命名函数

时间:2014-05-17 21:46:01

标签: javascript coffeescript

如果我想通过constructor.name获取函数的名称。

例如,在js中我们可以这样做:

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"

但在咖啡时,b = new Foo无法输出10,而是输出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"

但如果我像这样申报咖啡,a.constructor.name的输出是错误的:

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 >> ""

如何将上面的js代码翻译成咖啡?

2 个答案:

答案 0 :(得分:2)

  

如何将上面的js代码翻译成咖啡?

您将构造函数Foo中驻留的所有代码放在constructor类的Foo中:

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"

答案 1 :(得分:0)

CoffeeScript仅在与class语法一起使用时才会生成命名函数。 基本上,您的第一个代码段将转换为

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

而第二个将成为

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

This answer解释了这种代码生成背后的原因。

对于私有字段,你可以做一个类似于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"
相关问题