如何在不調用構造函數的情況下複製對象及其原型鏈?如何在不調用構造函數的情況下複製對象及其原型鏈?
換句話說,函數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