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

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

  getName: -> @_name

将变量放入类中使其成为静态成员,但如何使其成为非静态成员?是否有可能不“花哨”?

有帮助吗?

解决方案

是否有可能不“花哨”?

遗憾的是,你必须是 想要.

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

记住, “这只是 JavaScript。”

其他提示

类只是函数,因此它们创建范围。该范围内定义的所有内容从外部都是不可见的。

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

我想展示一些更奇特的东西

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

维塔利的答案有一个问题,那就是你无法定义你想要的变量 独特的 就范围而言,如果您以这种方式创建私有名称然后更改它,则该类的每个实例的名称值都会更改,因此我们可以通过一种方法来解决该问题

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

这是一个解决方案,借鉴了这里的其他几个答案加上 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

这是 我发现的关于设置的最好的文章 public static members, private static members, public 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

以下是如何在 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

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

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

由于咖啡脚本编译为 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

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

您无法使用 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() 之外,您不能通过任何其他方式从以这种方式创建的类继承。 实例化 将停止工作,并且以这种方式创建的对象会消耗更多的内存。另外,您不得使用 新的极好的 关键字不再。

要点是,每次实例化类时都必须创建闭包。纯 CoffeeScript 类中的成员闭包仅创建一次 - 即在构造类运行时“类型”时。

如果您只想将私有成员与公共成员分开,只需将其包装在 $ 变量中

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

并使用 @$.requirements

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top