不能在coffee-script中声明命名函数

Cannot declare named function in coffee-script

本文关键字:函数 声明 coffee-script 不能      更新时间:2023-09-26

如果我想通过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代码翻译成咖啡?

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

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

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"

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

while second将变成

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

这个答案稍微解释了这种代码生成背后的原因。

对于私有字段,你可以使用类似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"