如何在不调用构造函数的情况下复制对象及其原型链?如何在不调用构造函数的情况下复制对象及其原型链?
换句话说,函数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。
尽管在我的例子中只使用函数,我还需要属性。
您知道jsFiddle现在支持CoffeeScript了吗?使用左侧的**面板**菜单。 – 2011-12-19 20:26:19
我没有,太棒了! – 2011-12-19 20:32:26