I have a property named 'user-agent' in a javascript object that I'd like to get the value of. How do I do that in clojurescript?
(js/eval "a = {'user-agent': 'curl/7.22.0'}")
(js/eval "a['user-agent']") ;=> curl/7.22.0
(.-user-agent js/a) ;=> (returns nothing)
(. js/a -user-agent) ;=> (returns nothing)
Is this because properties are retrieved using dot notation instead of bracket notation here? https://github.com/clojure/clojurescript/blob/master/src/clj/cljs/compiler.clj#L734
Use aget
:
(aget js/a "user-agent")
The dot notation doesn't work because the clojurescript compiler does some name munging in order to support an extended in order to support characters such as ?
and !
in variable names. Among other things, the name munging also changes dashes to underscores, so that a field access such as (.-user-agent js/a)
gets compiled into something like a.user_agent
.
As long as you stay inside clojurescript, the name munging is transparent and you usually don't need to be aware of it, unless you are doing javascript interop. In that case, you can use the interpo features such as aget
and aset
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With