有人知道如何在CoffeeScript中创建私有的,非静态的成员吗?目前我正在这样做,它只使用一个以下划线开头的公共变量来澄清它不应该在类之外使用:
class Thing extends EventEmitter
constructor: (@_name) ->
getName: -> @_name
将变量放在类中使它成为静态成员,但是如何使其成为非静态成员?如果没有“花哨”,它甚至可能吗?
答案 0 :(得分: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);
答案 1 :(得分:20)
甚至可能没有“花哨”吗?
不幸的是,你必须要的看中的。
class Thing extends EventEmitter
constructor: (name) ->
@getName = -> name
请记住,“这只是JavaScript。”
答案 2 :(得分: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
答案 3 :(得分: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;
};
答案 4 :(得分: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
答案 5 :(得分:2)
Here's我发现有关设置.show()
,iOS
,public static members
以及其他一些相关内容的最佳文章。它涵盖了很多详细信息以及private static members
与public and private members
的比较。对于历史的原因,这里是最好的代码示例:
js
答案 6 :(得分: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
答案 7 :(得分: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'
但要小心将私有成员放在公共函数之前,因为coffee脚本将公共函数作为对象返回。看看编译好的Javascript:
EventEmitter = function() {
var privateName = "";
return {
setName: function(name) {
return privateName = name;
},
getName: function() {
return privateName;
}
};
};
答案 8 :(得分: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
当然,这与通过使用闭包可以拥有的所有其他私有变量具有相同的限制,例如,新添加的方法无法访问它们,因为它们未在同一范围内定义。 / p>
答案 9 :(得分: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 将停止工作,并且以这种方式创建的对象会占用更多内存。此外,您不能再使用新和超级关键字。
关键是,每次实例化类时都必须创建闭包。纯CoffeeScript类中的成员闭包只创建一次 - 也就是说,构造类运行时“type”时。
答案 10 :(得分:-3)
如果您只想要公开单独的私有成员,只需将其包装在$ variable
中$:
requirements:
{}
body: null
definitions: null
并使用@$.requirements