CoffeeScript中的私有成员?

84

有人知道如何在CoffeeScript中创建私有的非静态成员吗?目前,我正在使用以下方式,只是使用下划线开头的公共变量来澄清它不应该在类外部使用:

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

  getName: -> @_name

将变量放在类中会使其成为静态成员,但是如何使其成为非静态成员呢?如果不使用“花哨”的方法,是否可能实现?

11个回答

203

类本质上就是函数,因此它们会创建作用域。所有在该作用域内定义的内容都不会从外部可见。

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);

9
需要注意的是,这些私有变量对子类是不可用的。 - Ceasar
45
需要注意的是,如果要使用“私有”方法,则需要像 foo.call(this) 这样调用它,以便 this 成为函数的实例。这就是为什么在 JavaScript 中尝试模拟经典继承会变得复杂的原因。 - Jon Wingfield
3
另一个缺点是您无法访问“私有”方法以进行单元测试。 - nuc
16
私有方法是实现细节,通过调用它们的公有方法进行测试,因此私有方法不应该进行单元测试。如果一个私有方法看起来应该进行单元测试,那么它可能应该成为一个公有方法。参见这篇文章以获得更好的解释:https://dev59.com/92025IYBdhLWcg3w3J5H - mkelley33
2
还需要注意的是,在“公共”函数中使用之前,您需要在上面定义“私有”变量。否则,CoffeeScript会感到困惑并创建新的内部var声明,这将掩盖它们。 - Andrew Miner
显示剩余3条评论

20

没有"花哨"是不可能的吗?

遗憾的是,你必须要有点花哨

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

记住,“它只是 JavaScript。”


1
...所以你必须像在JS中一样去做。当它隐藏在所有的糖果后面时很容易忘记,谢谢! - thejh
4
真的是私有的吗?在类外仍然可以访问它。当执行a=Thing('a')后,a.getName()会返回值,而a.getName = ->'b'则会设置它。 - Amir
4
@Amir:name 只能从构造函数闭包内部访问。请看这个代码片段:https://gist.github.com/803810 - thejh
13
值得注意的是,@getName = -> name 似乎会破坏 getName 函数可能的继承性。 - Kendall Hopkins
12
这个答案是错误的:在这里,“getName”是公共的,而“name”仅可以从构造函数访问,因此它实际上并不是对象的“私有”属性。 - tothemario
显示剩余5条评论

11
我想展示更加高级的东西。
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

2
这里有一个解决方案,结合了其他答案和https://dev59.com/3nI-5IYBdhLWcg3wJEwK#7579956的方法。它将私有实例(非静态)变量存储在一个私有类(静态)数组中,并使用对象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

2
这是我发现的关于设置“公共静态成员”、“私有静态成员”、“公共和私有成员”以及其他相关内容的最佳文章(点击此处)。它涵盖了许多细节,还包括了js与coffee的比较。为了历史原因,这里有从中摘取的最佳代码示例:
# 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

2

Vitaly的回答有一个问题,那就是你不能定义你希望在作用域内是唯一的变量。如果你以这种方式创建了一个私有名称然后更改它,该名称的值将会对类的每个实例都更改,所以我们可以通过一种方式来解决这个问题。

# 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方法,就可以从外部访问names数组。

可以试一下。

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;
};

我喜欢这个实现。有什么缺点吗? - Erik5388

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

1
在CoffeeScript中,“class”会导致基于原型的结果。因此,即使您使用私有变量,它也会在实例之间共享。您可以这样做:
EventEmitter = ->
  privateName = ""

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

.. leads to

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

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

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

但是要小心,将私有成员放在公共函数之前,因为CoffeeScript返回公共函数作为对象。看一下编译后的JavaScript代码:

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

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

0

由于 CoffeeScript 编译成 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() 弹出 "one",我想要 "five"。 - thejh
@thejh 哦,抱歉,我现在看到错误了,昨天想这些东西可能太晚了。 - Ivo Wetzel
@thejh,我也遇到过这个问题,我在我的答案中尝试解决了它。 - iConnor

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类的伟大之处,因为你不能从以这种方式创建的类继承,除非再次使用extend()。 instanceof将停止工作,并且以这种方式创建的对象会消耗更多的内存。此外,您不再可以使用newsuper关键字。

关键是,闭包必须在每次实例化类时创建。纯CoffeeScript类中的成员闭包仅在构建类运行时“类型”时创建一次。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接