arcturo / library

A library of free eBooks we're working on

Home Page:http://arcturo.com/library/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Mixins example can yield to object collision

dperetti opened this issue · comments

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