ClojureScript interop

后端 未结 2 594
一整个雨季
一整个雨季 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条回答
  •  梦毁少年i
    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.

提交回复
热议问题