不能在coffee-script中声明命名函数
Cannot declare named function in coffee-script
如果我想通过constructor.name
获得一个函数的名称。
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"
相关文章:
- 直接在函数声明上使用function.prototype.bind
- 可以Resharper在我的javascript函数声明中添加分号
- 此行是否包含函数声明
- 函数声明与函数表达式之间的性能差异
- 为什么在javascript函数声明中使用逻辑运算符
- 函数声明未定义-原因
- JavaScript执行从函数声明开始,而不是从$(document).ready()开始
- 杰辛特 |传递默认设置 |函数声明和“this”
- 未知的 JavaScript 函数声明模式
- JavaScript 中的函数声明
- 在函数声明而不是运行时分析所有变量
- 命名函数声明有什么好处吗
- 将一个简单的函数声明形成JavaScript中的闭包
- 返回语句后的函数声明全局变量不会被覆盖
- (this)在函数声明之后
- 为什么使用 ||在变量函数声明中
- 为什么要将函数声明分配给命名变量
- 具有相同参数的 Javascript 函数声明
- 从性能的角度来看,函数声明与表达式
- 为什么 Mozilla Javascript 调试器的断点会捕捉到函数声明