繁体   English   中英

无法在coffee脚本中声明命名函数

[英]Cannot declare named function in coffee-script

如果我想通过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代码转换为咖啡?

你把所有驻留在构造函数的代码Fooconstructor一个的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"

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

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

对于私有字段,您可以执行类似于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"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM