3 ms·
> We've extended all objects including numbers to respond to the bar function.We can provide more specific implementations at anytime, i.e. by using extend-type
by ricardobeat 15y ago
> We've extended all objects including numbers to respond to the bar function.We can provide more specific implementations at anytime, i.e. by using extend-type on string, array, Vector, even your custom types
Mimicking that in javascript:
Object.defineProperty Object.prototype, 'bar',
value: -> 'whatever'
'foo'.bar()
(1).bar()
[1,2,3].bar()
More specific implementations can be defined on the other prototypes. This is totally safe (except for oldIE).
Making objects behave as functions (actually the opposite) is also possible:
MagicHash = (props) ->
f = (key) -> f[key]
f[k] = v for k,v of props
return f
address = new MagicHash
street: '1010 Foo Ave.'
apt: '1111'
city: 'Bit City'
zip: '000000000'
address.apt
#> '1111'
['street', 'zip'].map address
#> [ '1010 Foo Ave.', '000000000' ]
or
map = (fn, arr) -> arr.map fn
map address, ['street', 'zip']
#> [ '1010 Foo Ave.', '000000000' ]
And no, I have no idea how this could be useful...
- Tuna-Fish 15y ago>> We've extended all objects including numbers to respond to the bar function.We can provide more specific implementations at anytime, i.e. by using extend-type on string, array, Vector, even your custom types >Mimicking that in javascript: >This is totally safe (except for oldIE) No, not in his definition of safe it isn't. That's just monkeypatching -- the new functions are visible everywhere in the program, and it's entirely possible to be stung badly by name collisions. The ClojureScript version doesn't have these problems -- the protocol only exists in the namespaces where it is defined or imported.