如何在不调用其构造函数的情况下复制对象及其原型链?
换句话说,dup
以下示例中的函数会是什么样子?
class Animal
@sleep: -> console.log('sleep')
wake: -> console.log('wake')
end
class Cat extends Animal
constructor: ->
super
console.log('create')
attack: ->
console.log('attack')
end
cat = new Cat() #> create
cat.constructor.sleep() #> sleep
cat.wake() #> wake
cat.attack() #> attack
dup = (obj) ->
# what magic would give me an effective copy without
# calling the Cat constructor function again.
cat2 = dup(cat) #> nothing is printed!
cat2.constructor.sleep() #> sleep
cat2.wake() #> wake
cat2.attack() #> attack
尽管我看着很痛苦,但这里是这个例子的一个jsfiddle。
尽管在我的示例中只使用了函数,但我也需要这些属性。