Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
ECMAScript 6 proxies fun (method missing, negative array indexes)
# Ruby’s “method missing” analog with ES6 proxies.
proxify = (object) ->
new Proxy object, get: (receiver, name) ->
object[name] ? object.methodMissing.bind object, name
object = proxify
a: 1,
b: 15,
c: ->
'called'
methodMissing: (name, args...) ->
console.log "Calling missing method #{name} with arguments", args
console.log 'Accessing property "a":', object.a
console.log 'Accessing property "b":', object.b
console.log 'Calling method "c":', object.c()
object.methodName 1, 2, 3, 4
# Negative array indexes with ES6 direct proxies.
enableNegativeIndexes = (array) ->
new Proxy array, get: (receiver, name) ->
console.log 'Proxy#get', array, name
index = parseInt name
if not isNaN(index) and index < 0
array[array.length + index]
else
array[name]
# array = enableNegativeIndexes [100, 500, 600]
# array[-1] is 600
# => true
@zimdo

This comment has been minimized.

Copy link

commented Mar 19, 2012

have you tried this in an application?!? it is sure interesting but how expensive is it to wrap objects in a proxy!??

@paulmillr

This comment has been minimized.

Copy link
Owner Author

commented Mar 19, 2012

Just benchmarked this. Performance of proxies sucks: http://jsperf.com/proxy-cost.

The slowdown is x1000.

@zimdo

This comment has been minimized.

Copy link

commented Mar 19, 2012

@paulmillr

This comment has been minimized.

Copy link
Owner Author

commented Mar 19, 2012

Sadly, no. Firefox has __noSuchMethod__ but it's non-standard.

@zimdo

This comment has been minimized.

Copy link

commented Mar 19, 2012

yes and it doesn't work with nodejs since that uses v8 :(

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.