如何使用ClojureScript中的方法和构造函数创建JS对象 [英] How do I create an JS Object with methods and constructor in ClojureScript

查看:128
本文介绍了如何使用ClojureScript中的方法和构造函数创建JS对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设任务是在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 [abc])

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

(def x 2 3))

(.bar x 3); >> 9

问题:clojurescript中有更优雅/惯用的方式吗? strong>

解决方案

这是通过 JIRA CLJS-83 添加一个魔法对象协议到deftype:

  deftype Foo [abc] 
对象
(bar [this x](+ abcx)))
(def afoo(Foo。1 2 3))
); >> 9


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?

解决方案

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

这篇关于如何使用ClojureScript中的方法和构造函数创建JS对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆