Skip to content

Instantly share code, notes, and snippets.

@brendanberg
Created August 29, 2011 22:01
Show Gist options
  • Save brendanberg/1179527 to your computer and use it in GitHub Desktop.
Save brendanberg/1179527 to your computer and use it in GitHub Desktop.
Making objects using closures in CoffeeScript
point = (x, y) ->
setX = (nx) -> x = nx
setY = (ny) -> y = ny
(n) -> n(x, y, setX, setY)
pointGetX = ->
(x, y) -> x
pointGetY = ->
(x, y) -> y
pointAdd = (p2) ->
(x, y, setX, setY) ->
setX(x + p2 pointGetX())
setY(y + p2 pointGetY())
p1 = point(1, 2)
p2 = point(3, 5)
println (p1 pointGetX()) + ',' + p1(pointGetY())
println (p2 pointGetX()) + ',' + p2(pointGetY())
p1(pointAdd(p2))
println '---'
println p1(pointGetX()) + ',' + p1(pointGetY())
@nasser
Copy link

nasser commented Jan 21, 2012

point = proc { |x, y|
    proc { |sym| 
        (this = { 
            :set_x => proc { |nx| x = nx },
            :set_y => proc { |ny| y = ny },
            :get_x => proc { x },
            :get_y => proc { y },
            :get_n_y => proc { |n| n * y },

            :add => proc { |p2|
                this[:set_x].call(x + p2.call(:get_x).call())
                this[:set_y].call(y + p2.call(:get_y).call())

            }
        })[sym]
    }
}


p1 = point.call(4, 3)
p2 = point.call(6, 7)

p2.call(:add).call(p1)
puts p2.call(:get_x).call()
puts p1.call(:get_y).call()

p1 get_y

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment