Javascript 无法在coffee脚本中声明命名函数
如果我想通过Javascript 无法在coffee脚本中声明命名函数,javascript,coffeescript,Javascript,Coffeescript,如果我想通过构造函数.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_mem
构造函数.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=newfoo
不能输出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"
但是如果我像这样声明coffee,那么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?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"
如何将上面的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"
a)
.name
是非标准的,您无论如何都不应该使用它。b) 为什么不为构造函数使用class
语法(出于某种原因,您仍然使用new
调用Foo
)?@Bergi请参阅javascript第二行中的注释。哪一行是“我需要其他私有方法”?这将如何阻止您使用class
语法?@Bergi我更新了我的问题,请查看。请看a_public_方法部分。我已经知道咖啡为什么会产生这样的结果。我只需要一些代码来输出我期望的值,并且有一个可以在对象范围中访问的非静态私有属性,并且构造函数的行为正确。那么为什么不将您的non_static_private_member=10
移动到构造函数中呢?这将产生与JS代码片段相同的结果。我更新了我的问题,请查看。请参阅a\u public\u方法
部分。在构造函数中编写所有内容。这有点疯狂。这也是你在javascript函数中所做的。不管你疯不疯,谢谢。既然@YellowAfterlife首先更新了他的答案,我会接受他的,并投票支持你的答案。