Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/clojure/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/google-maps/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用ClojureScript中的方法和构造函数创建JS对象_Javascript_Clojure_Interop_Clojurescript - Fatal编程技术网

Javascript 如何使用ClojureScript中的方法和构造函数创建JS对象

Javascript 如何使用ClojureScript中的方法和构造函数创建JS对象,javascript,clojure,interop,clojurescript,Javascript,Clojure,Interop,Clojurescript,假设任务是在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

假设任务是在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    
实现这一目标的一个方法是:

    (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中是否有更优雅/惯用的上述方式?

(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
是实现这一点的惯用方法。

通过在deftype中添加一个神奇的“Object”协议解决了这一问题:

(deftype Foo [a b c]
  Object
  (bar [this x] (+ a b c x)))
(def afoo (Foo. 1 2 3))
(.bar afoo 3) ; >> 9

谢谢,它看起来很地道,但实际上你不能从js调用(我们正在构建js库):cljs.user.afoo.bar(3)在我们可以调用的地方:cljs.user.x.bar(3)为了从js端使用你的地道版本,你必须调用:cljs.user.afoo.cljs$user$IFoo$bar(null,3)我遗漏了什么吗?@user535149这真的是一个不同的问题。如果您想导出某些内容,请使用(defn^:export foo[…]…)^:export只要“something”是一个函数就可以工作。我想导出一个对象,其方法是在其原型上定义的。这将不是很有用,因为原型上的方法将是命名空间的。那么,使用clojurescript的惯用方法来创建一个具有构造函数的对象,原型上的方法是什么呢?我在原始问题中提出的方法是唯一的吗?请注意时间戳。这个答案实际上是在2012年1月26日(大约一年后)德诺伦给出的答案之后得出的,这看起来更优雅。