admin管理员组文章数量:1188035
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?
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?
Share Improve this question asked Jan 26, 2012 at 12:49 LambderLambder 2,9931 gold badge26 silver badges20 bronze badges2 Answers
Reset to default 20This 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
(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.
本文标签: javascriptHow do I create an JS Object with methods and constructor in ClojureScriptStack Overflow
版权声明:本文标题:javascript - How do I create an JS Object with methods and constructor in ClojureScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738388748a2084319.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论