是否有一种简单的方法可以在ClojureScript中列出JavaScript对象的属性和功能?
我尝试了以下内容:
(keys (js->clj (.getContext canvas "2d")))
但是这会引发以下错误:
ExceptionInfo #<Error: [object CanvasRenderingContext2D] is not ISeqable> clojure.core/ex-info (core.clj:4591)
答案 0 :(得分:10)
(js-keys (.getContext canvas "2d"))
这将列出JavaScript对象的所有函数和属性。
答案 1 :(得分:5)
您正在调用keys clojure函数,该函数返回(clojure)地图的键。要返回javascript对象的所有属性,您应该这样做:
(.keys js/Object myObject)
这是javascript代码的类比:
Object.keys(myObject);
修改: 我只是查看了js-&gt; clj - https://github.com/clojure/clojurescript/blob/master/src/main/cljs/cljs/core.cljs的来源,我也尝试使用canvas上下文。问题是画布上下文不是标准的js / Object,因此条件(相同的?(类型x)js / Object)不满足,js-&gt; clj函数最终在else分支中,这使得js-&gt; clj表现为身份函数,这意味着它只是在传递它时返回上下文。
这是源代码:
(defprotocol IEncodeClojure
(-js->clj [x options] "Transforms JavaScript values to Clojure"))
(defn js->clj
"Recursively transforms JavaScript arrays into ClojureScript
vectors, and JavaScript objects into ClojureScript maps. With
option ':keywordize-keys true' will convert object fields from
strings to keywords."
([x] (js->clj x {:keywordize-keys false}))
([x & opts]
(let [{:keys [keywordize-keys]} opts
keyfn (if keywordize-keys keyword str)
f (fn thisfn [x]
(cond
(satisfies? IEncodeClojure x)
(-js->clj x (apply array-map opts))
(seq? x)
(doall (map thisfn x))
(coll? x)
(into (empty x) (map thisfn x))
(array? x)
(vec (map thisfn x))
(identical? (type x) js/Object)
(into {} (for [k (js-keys x)]
[(keyfn k) (thisfn (aget x k))]))
:else x))]
(f x))))