2011-01-13 142 views
85

有人知道如何在CoffeeScript中创建私有的非静态成员吗​​?目前,我正在做这个,刚刚使用了公共变量开始用下划线澄清,它不应该之类的外部使用:CoffeeScript中的私人成员?

class Thing extends EventEmitter 
    constructor: (@_name) -> 

    getName: -> @_name 

把变量的类使静态成员,但我怎样才能使它非静态?它甚至可能没有变得“看中”?

回答

20

它甚至有可能没有得到“神奇”?

很遗憾地说,你必须是看中

class Thing extends EventEmitter 
    constructor: (name) -> 
    @getName = -> name 

记住,“这只是JavaScript的。”

+1

...所以你必须这样做,因为你会在JS中这样做。当它隐藏在所有糖后面时,很容易忘记它,谢谢! – thejh 2011-01-14 18:01:02

0

由于咖啡脚本编译为JavaScript,所以您可以拥有私有变量的唯一方法是通过闭包。

class Animal 
    foo = 2 # declare it inside the class so all prototypes share it through closure 
    constructor: (value) -> 
     foo = value 

    test: (meters) -> 
    alert foo 

e = new Animal(5); 
e.test() # 5 

这将编译向下通过下面的JavaScript:

var Animal, e; 
Animal = (function() { 
    var foo; // closured by test and the constructor 
    foo = 2; 
    function Animal(value) { 
    foo = value; 
    } 
    Animal.prototype.test = function(meters) { 
    return alert(foo); 
    }; 
    return Animal; 
})(); 

e = new Animal(5); 
e.test(); // 5 

当然这所有相同的限制,因为所有其他私有变量,你可以通过使用封闭的,例如,新添加的方法无法访问它们,因为它们没有在相同的范围内定义。

+9

这是一种静态成员。 `e = new Animal(5); f = new Animal(1); e.test()`提醒一个,我想要五个。 – thejh 2011-01-13 22:21:37

+0

@thejh哦,对不起,现在我看到了这个错误,猜想昨天想想这件事太晚了。 – 2011-01-14 07:22:26

+0

@thejh发生在我身上,我试图在我的答案中解决这个问题。 – iConnor 2014-02-24 03:09:55

204

类只是功能,所以他们创建范围。在此范围内定义的所有内容都不会从外部看到。

class Foo 
    # this will be our private method. it is invisible 
    # outside of the current scope 
    foo = -> "foo" 

    # this will be our public method. 
    # note that it is defined with ':' and not '=' 
    # '=' creates a *local* variable 
    # : adds a property to the class prototype 
    bar: -> foo() 

c = new Foo 

# this will return "foo" 
c.bar() 

# this will crash 
c.foo 

的CoffeeScript编译此为以下:

(function() { 
    var Foo, c; 

    Foo = (function() { 
    var foo; 

    function Foo() {} 

    foo = function() { 
     return "foo"; 
    }; 

    Foo.prototype.bar = function() { 
     return foo(); 
    }; 

    return Foo; 

    })(); 

    c = new Foo; 

    c.bar(); 

    c.foo(); 

}).call(this); 
0

你不能用CoffeeScript的类容易做,因为他们使用的JavaScript构造模式创建的类。

但是,你可以说这样的事情:

callMe = (f) -> f() 
extend = (a, b) -> a[m] = b[m] for m of b; a 

class superclass 
    constructor: (@extra) -> 
    method: (x) -> alert "hello world! #{x}#{@extra}" 

subclass = (args...) -> extend (new superclass args...), callMe -> 
    privateVar = 1 

    getter: -> privateVar 
    setter: (newVal) -> privateVar = newVal 
    method2: (x) -> @method "#{x} foo and " 

instance = subclass 'bar' 
instance.setter 123 
instance2 = subclass 'baz' 
instance2.setter 432 

instance.method2 "#{instance.getter()} <-> #{instance2.getter()} ! also, " 
alert "but: #{instance.privateVar} <-> #{instance2.privateVar}" 

但是你使用扩展失去的CoffeeScript类的伟大,因为你不能从任何其他方式创建的方法比类继承( )。 instanceof将停止工作,并且以此方式创建的对象消耗更多内存。此外,您不能再使用新的超级关键字。

的一点是,该关闭必须创建每次类实例化时间。纯CoffeeScript类中的成员闭包只创建一次 - 也就是说,构建类运行时“类型”时。

10

我想展示一些东西更炫

class Thing extends EventEmitter 
    constructor: (nm) -> 
    _name = nm 
    Object.defineProperty @, 'name', 
     get: -> 
     _name 
     set: (val) -> 
     _name = val 
     enumerable: true 
     configurable: true 

现在你可以做

t = new Thing('Dropin') 
# members can be accessed like properties with the protection from getter/setter functions! 
t.name = 'Dragout' 
console.log t.name 
# no way to access the private member 
console.log t._name 
-3

如果你想从公共只有独立的私人承包商,客人,只是把它包在$变量

$: 
     requirements: 
       {} 
     body: null 
     definitions: null 

and use @$.requirements

2

维塔利的答案有一个问题,那就是你不能定义你想成为范围的唯一的变量,如果你这样做了一个私人名称然后改变了它,名称值会改变为每一个单一的类的实例,所以有一个办法可以解决这个问题

# create a function that will pretend to be our class 
MyClass = -> 

    # this has created a new scope 
    # define our private varibles 
    names = ['joe', 'jerry'] 

    # the names array will be different for every single instance of the class 
    # so that solves our problem 

    # define our REAL class 
    class InnerMyClass 

     # test function 
     getNames: -> 
      return names; 

    # return new instance of our class 
    new InnerMyClass 

这不是不可能从外部访问的名字排列,除非您使用getNames

测试了这一点

test = new MyClass; 

tempNames = test.getNames() 

tempNames # is ['joe', 'jerry'] 

# add a new value 
tempNames.push 'john' 

# now get the names again 
newNames = test.getNames(); 

# the value of newNames is now 
['joe', 'jerry', 'john'] 

# now to check a new instance has a new clean names array 
newInstance = new MyClass 
newInstance.getNames() # === ['joe', 'jerry'] 


# test should not be affected 
test.getNames() # === ['joe', 'jerry', 'john'] 

编译的JavaScript

var MyClass; 

MyClass = function() { 
    var names; 
    names = ['joe', 'jerry']; 
    MyClass = (function() { 

    MyClass.name = 'MyClass'; 

    function MyClass() {} 

    MyClass.prototype.getNames = function() { 
     return names; 
    }; 

    return MyClass; 

    })(); 
    return new MyClass; 
}; 
1

这里是如何在CoffeeScript中
声明私有,非静态成员对于完全参考,你可以看看https://github.com/vhmh2005/jsClass

class Class 

    # private members 
    # note: '=' is used to define private members 
    # naming convention for private members is _camelCase 

    _privateProperty = 0 

    _privateMethod = (value) ->   
    _privateProperty = value 
    return 

    # example of _privateProperty set up in class constructor 
    constructor: (privateProperty, @publicProperty) -> 
    _privateProperty = privateProperty 
2

下面是一个解决方案这里引用了其他几个答案,加上https://stackoverflow.com/a/7579956/1484513。它将私有实例(非静态)变量存储在私有类(静态)数组中,并使用对象ID来知道该数组的哪个元素包含属于每个实例的数据。

# Add IDs to classes. 
(-> 
    i = 1 
    Object.defineProperty Object.prototype, "__id", { writable:true } 
    Object.defineProperty Object.prototype, "_id", { get: -> @__id ?= i++ } 
)() 

class MyClass 
    # Private attribute storage. 
    __ = [] 

    # Private class (static) variables. 
    _a = null 
    _b = null 

    # Public instance attributes. 
    c: null 

    # Private functions. 
    _getA = -> a 

    # Public methods. 
    getB: -> _b 
    getD: -> __[@._id].d 

    constructor: (a,b,@c,d) -> 
    _a = a 
    _b = b 

    # Private instance attributes. 
    __[@._id] = {d:d} 

# Test 

test1 = new MyClass 's', 't', 'u', 'v' 
console.log 'test1', test1.getB(), test1.c, test1.getD() # test1 t u v 

test2 = new MyClass 'W', 'X', 'Y', 'Z' 
console.log 'test2', test2.getB(), test2.c, test2.getD() # test2 X Y Z 

console.log 'test1', test1.getB(), test1.c, test1.getD() # test1 X u v 

console.log test1.a   # undefined 
console.log test1._a  # undefined 

# Test sub-classes. 

class AnotherClass extends MyClass 

test1 = new AnotherClass 's', 't', 'u', 'v' 
console.log 'test1', test1.getB(), test1.c, test1.getD() # test1 t u v 

test2 = new AnotherClass 'W', 'X', 'Y', 'Z' 
console.log 'test2', test2.getB(), test2.c, test2.getD() # test2 X Y Z 

console.log 'test1', test1.getB(), test1.c, test1.getD() # test1 X u v 

console.log test1.a   # undefined 
console.log test1._a  # undefined 
console.log test1.getA() # fatal error 
1

Here's我发现有关设置public static membersprivate static memberspublic and private members,以及其他一些相关的东西的最好的文章。它涵盖了很多细节,jscoffee比较。而对于历史原因,这里是最好的代码示例从它:

# CoffeeScript 

class Square 

    # private static variable 
    counter = 0 

    # private static method 
    countInstance = -> 
     counter++; return 

    # public static method 
    @instanceCount = -> 
     counter 

    constructor: (side) -> 

     countInstance() 

     # side is already a private variable, 
     # we define a private variable `self` to avoid evil `this` 

     self = this 

     # private method 
     logChange = -> 
      console.log "Side is set to #{side}" 

     # public methods 
     self.setSide = (v) -> 
      side = v 
      logChange() 

     self.area = -> 
      side * side 

s1 = new Square(2) 
console.log s1.area() # output 4 

s2 = new Square(3) 
console.log s2.area() # output 9 

s2.setSide 4   # output Side is set to 4 
console.log s2.area() # output 16 

console.log Square.instanceCount() # output 2 
1

“类”咖啡脚本导致了基于原型的结果。因此,即使您使用私有变量,它也会在实例之间共享。你可以这样做:

EventEmitter = -> 
    privateName = "" 

    setName: (name) -> privateName = name 
    getName: -> privateName 

..导致

emitter1 = new EventEmitter() 
emitter1.setName 'Name1' 

emitter2 = new EventEmitter() 
emitter2.setName 'Name2' 

console.log emitter1.getName() # 'Name1' 
console.log emitter2.getName() # 'Name2' 

但要小心,把公共职能前的私有成员,因为咖啡脚本返回的公共职能为目标。看看编译的Javascript:

EventEmitter = function() { 
    var privateName = ""; 

    return { 
    setName: function(name) { 
     return privateName = name; 
    }, 
    getName: function() { 
     return privateName; 
    } 
    }; 
};