12

タスクがclojurescriptでユーティリティライブラリを作成してJSから使用できるようにすることだと想像してください。

たとえば、次と同等のものを作成したいとします。

    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    

私が持ってきたそれを達成するための1つの方法は次のとおりです。

    (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

質問:clojurescriptに上記のよりエレガントで慣用的な方法はありますか?

4

2 に答える 2

20

これは、魔法の「オブジェクト」プロトコルを deftype に追加することで、JIRA CLJS-83で解決されました。

(deftype Foo [a b c]
  Object
  (bar [this x] (+ a b c x)))
(def afoo (Foo. 1 2 3))
(.bar afoo 3) ; >> 9
于 2013-01-02T21:20:19.380 に答える
12
(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

これを行う慣用的な方法です。

于 2012-01-26T16:58:08.660 に答える