Mixins example can yield to object collision
dperetti opened this issue · comments
dperetti commented
The objects need to be cloned before being added in order to prevent different classes extending the same mixin from referencing the same properties.
The example needs to be amended as such :
clone = (obj) ->
if not obj? or typeof obj isnt 'object'
return obj
newInstance = new obj.constructor()
for key of obj
newInstance[key] = clone obj[key]
return newInstance
moduleKeywords = ['extended', 'included']
class Module
@extend: (obj) ->
for key, value of obj when key not in moduleKeywords
@[key] = clone value
obj.extended?.apply(@)
this
@include: (obj) ->
for key, value of obj when key not in moduleKeywords
@::[key] = clone value
obj.included?.apply(@)
this