Howto override toString of defrecord instances in ClojureScript?

1,565 views
Skip to first unread message

r0man

unread,
Nov 24, 2011, 7:45:40 AM11/24/11
to clo...@googlegroups.com
Hello,

what's the preferred way to override the toString method of a
ClojureScript record? I could use set! to change the toString fn
of a record after it has been initialized like this:

(defrecord MyRecord [name])

(let [record (MyRecord. "Hello World")]
  (set! record.toString (fn [] (:name (js* "this"))))
  (str record))

But I wonder if there is something more idiomatic? Can I change
the toString method in the prototype of the record directly? How
do get the prototype?

Thank you, Roman.

Baishampayan Ghose

unread,
Nov 24, 2011, 7:55:45 AM11/24/11
to clo...@googlegroups.com
> what's the preferred way to override the toString method of a
> ClojureScript record? I could use set! to change the toString fn
> of a record after it has been initialized like this:
>
> (defrecord MyRecord [name])
>
> (let [record (MyRecord. "Hello World")]
>   (set! record.toString (fn [] (:name (js* "this"))))
>   (str record))

Not unlike Clojure, you can extend ClojureScript types to Object & nil as well.

So you can do something like this -

(defrecord MyRecord [name]
Object
(toString [_] name))

Regards,
BG

--
Baishampayan Ghose
b.ghose at gmail.com

r0man

unread,
Nov 24, 2011, 8:24:45 AM11/24/11
to clo...@googlegroups.com
Thank you, Baishampayan. That's exactly what I was looking for ...
Reply all
Reply to author
Forward
0 new messages