ClojureScript interop

后端 未结 2 591
一整个雨季
一整个雨季 2021-02-05 16:27

I am trying to find out how to access Javascript objects properties in ClojureScript. If I know in advance the name of the property, that is easy. To get foo.bar I

相关标签:
2条回答
  • 2021-02-05 17:00

    You can use aget / aset to access properties known only at runtime.

    ;; Use clj->js to convert clj(s) map to javascript.
    ;; Note the #js {:bar 100} reader literal indicating a js map.
    
    cljs.user> (def foo (clj->js {:bar 100}))
    #js {:bar 100}
    cljs.user> (.-bar foo) 
    100
    cljs.user> (aget foo "bar")
    100
    cljs.user> (aset foo "baz" 200)
    200
    cljs.user> (.-baz foo) 
    200
    
    0 讨论(0)
  • 2021-02-05 17:04

    Using string names may be also important in case when you want to take advantage of :optimizations :advanced compiler mode, but you don't have externs file covering your code.

    See David Nolen's example using goog.object.get: https://github.com/clojure/clojurescript/wiki/Dependencies#using-string-names

    While aget works. This method was originally supposed to provide you access to array elements, not properties of js objects in general. goog.object's get method is a better way to communicate your intent.

    Here are the implementations of both methods: https://github.com/google/closure-library/blob/1b8a893271d790626b5cd652b922675c987f106d/closure/goog/object/object.js#L403

    https://github.com/clojure/clojurescript/blob/d2d031605b1ad552077218c8f445868653c01744/src/main/clojure/cljs/core.cljc#L942

    As you can see, (aget o key)generates javascript code o[key] directly, but goog.object.get calls a method which first checks if the key is present in o.

    0 讨论(0)
提交回复
热议问题