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

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

问题描述

想象一下,任务是在 clojurescript 中创建一些实用程序库,以便它可以从 JS 中使用.

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    

实现它的一种方法是:

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

推荐答案

此问题已通过 解决JIRA CLJS-83 通过向 deftype 添加一个神奇的对象"协议:

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天全站免登陆