Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create an JS Object with methods and constructor in ClojureScript

Imagine the task is to create some utility lib in clojurescript so it can be used from JS.

For example, let's say I want to produce an equivalent of:

    var Foo = function(a, b, c){
      this.a = a;
      this.b = b;
      this.c = c;    
    }

    Foo.prototype.bar = function(x){
      return this.a + this.b + this.c + x;
    }

    var x = new Foo(1,2,3);

    x.bar(3);           //  >>  9    

One way to achieve it I came with is:

    (deftype Foo [a b c])   

    (set! (.bar (.prototype Foo)) 
      (fn [x] 
        (this-as this
          (+ (.a this) (.b this) (.c this) x))))

    (def x (Foo. 1 2 3))

    (.bar x 3)     ; >> 9

Question: is there more elegant/idiomatic way of the above in clojurescript?

like image 435
Lambder Avatar asked Jan 26 '12 12:01

Lambder


People also ask

How do you create an object in JavaScript What are some of the built in methods in JavaScript?

Creating a JavaScript ObjectCreate a single object, using an object literal. Create a single object, with the keyword new . Define an object constructor, and then create objects of the constructed type. Create an object using Object.create() .

How do you create a new object from a class in JavaScript?

To create an object, use the new keyword with Object() constructor, like this: const person = new Object(); Now, to add properties to this object, we have to do something like this: person.


2 Answers

This was solved with JIRA CLJS-83 by adding a magic "Object" protocol to the deftype:

(deftype Foo [a b c]
  Object
  (bar [this x] (+ a b c x)))
(def afoo (Foo. 1 2 3))
(.bar afoo 3) ; >> 9
like image 64
kanaka Avatar answered Oct 15 '22 08:10

kanaka


(defprotocol IFoo
  (bar [this x]))

(deftype Foo [a b c]
  IFoo
  (bar [_ x]
    (+ a b c x)))

(def afoo (Foo. 1 2 3))
(bar afoo 3) ; >> 9

Is the idiomatic way to do this.

like image 20
dnolen Avatar answered Oct 15 '22 09:10

dnolen