浏览器功能 - 检查 ClojureScript 中是否存在对象

Browser capabilities - check if object exists in ClojureScript

测试 ClojureScript 中是否存在某些内容的方法是什么?例如,我正在尝试访问浏览器地理定位 API。在 javascript 中,我会做一个简单的检查:

// check for Geolocation support
if (navigator.geolocation) {
  console.log('Geolocation is supported!');
}
else {
  console.log('Geolocation is not supported for this Browser/OS version yet.');
}

但是将其转换为 ClojureScript 时出现错误:

(if (js/navigator.geolocation)  ;; Uncaught TypeError: navigator.geolocation is not a function
   (println "Geolocation is supported")
   (println "Geolocation is not supported"))

在 ClojureScript 中检查浏览器功能的正确方法是什么?

目前,我正在使用:

(if (not (nil? js/navigator.geolocation))
    (println "Geolocation is supported")
    (println "Geolocation is not supported"))

不确定这是否 idiomatic/cover 所有用例,我很乐意接受另一个有适当解释的答案。

有多个选项:

  1. exists?: http://dev.clojure.org/jira/browse/CLJS-495

只存在于 clojurescript 中,不存在于 clojure 中。 如果您查看宏 in core.cljc,您会发现它只是一个 if( typeof ... !== 'undefined' )。 使用示例:

   (if (exists? js/navigator.geolocation)
      (println "Geolocation is supported"))
      (println "Geolocation is not supported"))
  1. (js-in "geolocation" js/window) 扩展为 "geolocation" in windows.

  2. (undefined? js/window.geolocation) 扩展为 void 0 === window.geolocation

IMO,正确的是js-in