Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending the constructor of a deftype in clojurescript

When creating a type via deftype in clojurescript:

(deftype SomeObject [a b c]
    Object
        (update [_]
            (set! (.-a _) 5)
            (set! (.-b _) 6) ))

Is there a possibility to extend the constructor? I would like to do some initialization of my object when it's being created!

like image 773
devboy Avatar asked Oct 30 '25 12:10

devboy


1 Answers

There is no support for that in deftype, no; the Clojure(Script) equivalent is to define a factory function, perhaps make-some-object, and use that instead of the actual constructor. See amalloy's answer for an example and rationale.

Of course in JavaScript, constructors are simply functions and you can certainly use ClojureScript to define a function which will work as a JS constructor would:

;; "constructor" with default field values
(defn Point [x y]
  (this-as this
    (set! (.-x this) (if x x 10)) ; NB. Clojure truth semantics are used
    (set! (.-y this) (if y y 20))))

(.-x (Point. 2))
;= 2
(.-y (Point. 2))
;= 20

That goes against the overall spirit of the language a bit, and so is not advisable except in special circumstances. (Interop with a JS API expecting a constructor as an argument perhaps?)

like image 136
Michał Marczyk Avatar answered Nov 01 '25 01:11

Michał Marczyk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!