gpt4 book ai didi

javascript - 迭代用户选项并将它们分配给 CoffeeScript 中的对象实例

转载 作者:行者123 更新时间:2023-12-02 18:56:39 25 4
gpt4 key购买 nike

假设我在 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'

如果我要跨对象的多个实例打印名称属性,我总是会得到相同的值:

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, ... )

最佳答案

这应该有效:

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'

关于javascript - 迭代用户选项并将它们分配给 CoffeeScript 中的对象实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15273529/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com