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

nha*_*nha 3 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.');
}
Run Code Online (Sandbox Code Playgroud)

但是将它翻译成ClojureScript,我收到一个错误:

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

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

Clo*_*tly 6

有多种选择:

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

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

   (if (exists? js/navigator.geolocation)
      (println "Geolocation is supported"))
      (println "Geolocation is not supported"))
Run Code Online (Sandbox Code Playgroud)
  1. (js-in "geolocation" js/window)扩展到"geolocation" in windows.

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

IMO,正确的是js-in.