Idiomatic way of accessing JavaScript properties in nested "namespaces"

已查看 480 次
跳至第一个未读帖子

Rafal Spacjer

未读,
2014年8月28日 16:22:532014/8/28
收件人 clojur...@googlegroups.com
Hello,

I' curious what is a preferable way of accessing properties or methods in nested JavaScript "namespaces".

Lets assume that external library define such property:

Foo.Bar.Foo2.myProperty in global namespace.

what is idiomatic way of accessing 'myProperty':

(.-myProperty js/Foo.Bar.Foo2)

or

(.. js/Foo -Bar -Foo2 -myProperty)

Same question for a method, if we have such statement:

Foo.Bar.Foo2.myMethod();

how should we invoke 'myMethod'? Is this correct: (.myMethod js/Foo.Bar.Foo2) ?

Francis Avila

未读,
2014年8月28日 17:45:552014/8/28
收件人 clojur...@googlegroups.com
Avoid dots in the name part of symbols. "js/a.b.c" works to reference "a.b.c" by value (i.e. without calling it), but it's not idiomatic. Prefer (.. js/a -b -c), or using your examples:

(.. js/Foo -Bar -Foo2 -myProperty)

(.. js/Foo -Bar -Foo2 myMethod)

The "js" pseudo-namespace is special because it emits the symbol as normal js property access, but if it were a *real* namespace there would be no dotted symbols in it. (That said, I cheat all the time e.g. with "(js/console.log x)".)

Ivan L

未读,
2014年8月28日 20:20:392014/8/28
收件人 clojur...@googlegroups.com
why is it not considered idiomatic, I see that pattern used all the time. Doesn't clojure itself use fq namespaces occasionally? (just no js prefix)

Rafal Spacjer

未读,
2014年8月29日 01:09:362014/8/29
收件人 clojur...@googlegroups.com
Sounds good, thank you. Of course I agree, that using dots (like in "(js/console.log x)") is faster to write.

Rafal Spacjer

未读,
2014年8月29日 13:37:322014/8/29
收件人 clojur...@googlegroups.com
On the other hand, I've found this JIRA bug: http://dev.clojure.org/jira/browse/CLJS-455

with the comment of David Nolen:
"This patch creates issues around using constructors provided by libraries outside ClojureScript and GClosure. Also from Rich's original commit support js prefix, it seems like JS style access after the / was actually intended"

so maybe using dots after js/ is allowed

Francis Avila

未读,
2014年8月29日 14:37:302014/8/29
收件人 clojur...@googlegroups.com
There's no question that it's allowed. You can use js/a.b.c

However, it is *less idiomatic* because there's no analogous construct in Clojure (not ClojureScript) code. In Clojure, a symbol referencing a var in a namespace will only ever have a name part without dots.

The fact that the CLJS-445 patch to warn on dotted name parts of "js/name" constructs was initially accepted by Nolan in the first place is itself evidence that this construct is less idiomatic.

Either way it's not a big deal. No one is going to get too upset if you use js/a.b.c instead of (.. js/a -b -c)

Rafal Spacjer

未读,
2014年8月29日 16:19:392014/8/29
收件人 clojur...@googlegroups.com
Fully agree, thank you for helping me.
回复全部
回复作者
转发
0 个新帖子