Skip to content

Instantly share code, notes, and snippets.

@paulmillr
Created January 20, 2012 16:27
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paulmillr/1648257 to your computer and use it in GitHub Desktop.
Save paulmillr/1648257 to your computer and use it in GitHub Desktop.
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
Copy link

zimdo 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
Copy link
Author

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

The slowdown is x1000.

@zimdo
Copy link

zimdo commented Mar 19, 2012 via email

@paulmillr
Copy link
Author

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

@zimdo
Copy link

zimdo 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