[英]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代码转换为咖啡?
你把所有驻留在构造函数的代码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"
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.