In clojureScript the following multi-arity function
(defn sum [& xs] (reduce + xs))
can be either called via (sum 4 6 9)
or by the use of (apply sum [4 6 9])
which yields the same result.
How can this be done with a native JavaScript function, such as: console.log
.
(apply js/console.log [1 2 3])
This, yields the following error:
#object[TypeError TypeError: 'log' called on an object that does not implement interface Console.]
Some browsers always assuming the this
is certain object, you can use .bind
in js for temporal fix.
; you can use .bind on any function
(def d (.bind (.-log js/console) js/console))
(def ms ["aaa" "bbb" "barbarbar"])
(mapv d ms)
What does this statement do? console.log.bind(console)
Why do js functions fail when I assign them to a local variable?
There might be an error in your code. apply
works totally fine out of the box for JS functions:
cljs.user=> (apply js/Math.sqrt [25])
5
You can test it with this online REPL and I also tested it in my local project -- no problems so far.
cljs.user=> (apply js/console.log [1 2 3])
nil
also prints the output in the normal JS console as expected.
Using js/ab
only works when a
is global in your environment. Either way, I find this much cleaner:
(apply (.-log js/console) [1 2 3])
Note: with member functions, don't forget the first argument is this
.
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.