假设我在CoffeeScript中有这个类:
class Human
constructor: ( options ) ->
if options
for property of options
opts[ property ] = options[ property ]
printName: ->
console.log 'My name is ' + opts.name
opts =
name: 'foo'
如果我要在对象的多个实例中打印出name属性,我总会得到相同的值:
a = new Human({name: 'bob'})
b = new Human({name: 'john'})
// a.printName() -> john
// b.printName() -> john
但我想单独保存每个实例的值,如下所示:
// a.printName() -> bob
// b.printName() -> john
现在我知道我必须使用this.name
,但是如何使用方法迭代一长串值并将它们分配给对象实例来实现呢?我不想像这样污染构造函数
constructor: ( @name, @surname, @age, ... )
答案 0 :(得分:2)
这应该有效:
class Human
constructor: ( options ) ->
@opts = default_ops
if options
for property of options
@opts[ property ] = options[ property ]
printName: ->
console.log 'My name is ' + @opts.name
default_ops =
name: 'foo'
答案 1 :(得分:0)
好的,将对象作为参数传递给构造函数作为参考。感谢Amber的领导。
class Human
constructor: ( @opts, options ) ->
if options
for property of options
@opts[ property ] = options[ property ]
printName: ->
console.log 'My name is ' + @opts.name
@opts =
name: 'foo'
答案 2 :(得分:0)
使用underscore
(或提供extend
的任何其他lib - 类似功能)的一些帮助,您可以非常简单易读地编写它:
class Human
DEFAULTS:
name: 'default name'
constructor: (opts = {}) ->
@opts = _.extend {}, @DEFAULTS, opts
printName: ->
console.log 'My name is ' + @opts.name
顺便说一句,您可以将道具直接附加到实例:
class Human
DEFAULTS:
name: 'default name'
constructor: (opts = {}) ->
_.extend @, @DEFAULTS, opts
printName: ->
console.log 'My name is ' + @name