ClojureScript – 将任意JavaScript对象转换为Clojure Script映射

我试图将Javascript对象转换为Clojure.但是,我收到以下错误:

 (js/console.log (js->clj e)) ;; has no effect
 (pprint (js->clj e)) ;; No protocol method IWriter.-write defined for type object: [object Geoposition]

是的,这个对象来自Geolocation API.我想我必须扩展IEncodeClojure和IWriter,但我不知道如何.

例如,添加以下内容:

(extend-protocol IEncodeClojure
  Coordinates
  (-js->clj [x options]
    (println "HERE " x options)))

加载我的代码时产生错误:Uncaught TypeError:无法读取undefined的属性’prototype’

js-> clj仅适用于Object,任何带有自定义构造函数(请参阅类型)的内容都将按原样返回.

见:https://github.com/clojure/clojurescript/blob/master/src/main/cljs/cljs/core.cljs#L9319

我建议这样做:

(defn jsx->clj
  [x]
  (into {} (for [k (.keys js/Object x)] [k (aget x k)])))

更新正确的解决方案请参阅Aaron的回答,必须使用goog.object

翻译自:https://stackoverflow.com/questions/32467299/clojurescript-convert-arbitrary-javascript-object-to-clojure-script-map

转载注明原文:ClojureScript – 将任意JavaScript对象转换为Clojure Script映射