84

誰かがCoffeeScriptで非静的なプライベートメンバーを作成する方法を知っていますか?現在、私はこれを行っています。これは、アンダースコアで始まるパブリック変数を使用して、クラスの外部で使用してはならないことを明確にします。

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

  getName: -> @_name

変数をクラスに入れると静的メンバーになりますが、どうすれば非静的にすることができますか?「ファンシー」にならずにそれも可能ですか?

4

11 に答える 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);
于 2011-11-30T23:12:24.097 に答える
20

「派手」にならなくても可能ですか?

悲しいことに、あなたは派手でなければなりません。

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

「これは単なる JavaScript です」ということを覚えておいてください。

于 2011-01-13T23:02:14.243 に答える
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
于 2012-09-26T05:54:02.303 に答える
2

public static membersこれは、 、private static memberspublic and private members、およびその他の関連するものの設定についてが見つけた最高の記事です。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
于 2015-06-01T14:41:39.203 に答える
2

Vitaly の回答には 1 つの問題があります。それは、スコープに一意にする変数を定義できないことです。そのようにプライベート名を作成してから変更すると、クラスのインスタンスごとに名前の値が変更されます。その問題を解決する方法が 1 つあります

# 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;
};
于 2014-02-24T03:02:55.110 に答える
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
于 2014-11-23T13:35:31.483 に答える
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
于 2014-07-17T08:47:14.373 に答える
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;
    }
  };
};
于 2015-08-06T15:42:54.803 に答える
0

クラスの作成に Javascript コンストラクター パターンを使用するため、CoffeeScript クラスでは簡単に行うことができません。

ただし、次のように言うこともできます。

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は機能しなくなり、この方法で作成されたオブジェクトは少し多くのメモリを消費します。また、newおよびsuperキーワードは使用しないでください。

ポイントは、クラスがインスタンス化されるたびにクロージャーを作成する必要があるということです。純粋な CoffeeScript クラスのメンバー クロージャは、一度だけ作成されます。つまり、クラス ランタイムの「型」が構築されるときです。

于 2012-06-02T20:59:09.967 に答える
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

もちろん、これには、クロージャーを使用して持つことができる他のすべてのプライベート変数と同じ制限があります。たとえば、新しく追加されたメソッドは、同じスコープで定義されていないため、それらにアクセスできません。

于 2011-01-13T22:06:12.977 に答える
-3

パブリック メンバーからプライベート メンバーのみを分離したい場合は、$ 変数でラップするだけです

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

と使用@$.requirements

于 2013-02-19T16:11:20.003 に答える