【发布时间】: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 部分。