【问题标题】:Cannot declare named function in coffee-script无法在咖啡脚本中声明命名函数
【发布时间】:2014-05-17 21:46:00
【问题描述】:

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

【问题讨论】:

  • a) .name 是非标准的,无论如何你都不应该使用它。 b) 为什么不对构造函数使用class 语法(出于某种原因,您仍然使用new 调用Foo)?
  • @Bergi 请参阅 javascript 第二行中的注释。
  • 哪一个,“我需要其他私有方法”?这将如何阻止您使用 class 语法?
  • @Bergi 我更新了我的问题,请看。请参阅 a_public_method 部分。

标签: javascript coffeescript


【解决方案1】:

上面的js代码怎么翻译成coffee?

您将驻留在构造函数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"

【讨论】:

  • 在构造函数中写入所有内容。这有点疯狂。
  • 嗯,这也是您在 javascript 函数中所做的。疯狂与否。
  • 好的,谢谢。由于@YellowAfterlife 首先更新了他的答案,我会接受他的,并投票给你的。
【解决方案2】:

CoffeeScript 只会在与 class 语法一起使用时生成命名函数。 基本上,您的第一个 sn-p 将转换为

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"

【讨论】:

  • 我已经知道为什么咖啡会产生类似的东西的细节。我只需要一些代码来输出我期望的值,并且有一个可以在对象范围内访问的非静态私有属性,并且构造函数的行为正确。
  • 为什么不把你的non_static_private_member = 10 移到构造函数中呢?这将产生与 JS sn-p 相同的结果。
  • 我更新了我的问题,请看。请参阅a_public_method 部分。
猜你喜欢
  • 1970-01-01
  • 2015-09-12
  • 1970-01-01
  • 2017-04-05
  • 2011-09-15
  • 1970-01-01
  • 2012-10-13
  • 2016-08-23
相关资源
最近更新 更多