测试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中检查浏览器功能的正确方法是什么?
有多种选择:
只存在于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)
(js-in "geolocation" js/window)扩展到"geolocation" in windows.
(undefined? js/window.geolocation) 扩展到 void 0 === window.geolocation
IMO,正确的是js-in.
| 归档时间: |
|
| 查看次数: |
581 次 |
| 最近记录: |