Вопрос

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 just do

(.-bar foo)

Is there a way to access a property whose name is known only at runtime? I am looking for the equivalent of the JS syntax foo[dynamicBar]

Это было полезно?

Решение

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

Другие советы

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top