简体   繁体   中英

What is the ClojureScript analogue of setting an object value that didn't exist to null from JavaScript?

I'm seeing lots of code using the pattern:

if (typeof a.b === 'undefined') {
  a.b = null;

Now I'm translating this to:

(if (not (exists (.-b a)))
  (aset a b nil)

But I feel like I should be setting this to:

(if (not (exists (.-b a)))
  (aset a b (clj->js {}))

(Because the compiler may eliminate the step entirely in the former case).

Is that appropriate - or am I losing some crucial data?

My question is: What is the ClojureScript analogue of setting an object value that didn't exist to null from JavaScript?

First, if attempting to imitate some JavaScript, I'd recommend the :repl-verbose option, as it makes it very easy to try variants at the REPL and immediately see the resulting JavaScript.

If you want to exactly imitate your code, then set! will do the trick:

(when (not (exists? (.-b js/a)))
  (set! (.-b js/a) nil))

produces

((!(typeof a.b !== 'undefined'))?a.b = null:null)

But (and perhaps this is the same as the concern raised over compiler behavior), to avoid renaming during Closure optimizations (see this SO ), aget and aset can be used with a string-based index:

(when (not (exists? (aget js/a "b")))
  (aset js/a "b" nil))

((!(typeof (a["b"]) !== 'undefined'))?(a["b"] = null):null)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM