Fork me on GitHub
#clojurescript
<
2018-06-23
>
pesterhazy14:06:59

Javascript question (but related to CLJS): This works:

const URL=require("url").URL; new URL("")
but this doesn't:
new require("url").URL("")

pesterhazy14:06:43

is there no way to instantiate a class like that without a temporary assignment (in JS or CLJS)?

justinlee15:06:55

@pesterhazy Have tried adding parens? New might bind before dot. (Sorry on Mobile)

pesterhazy15:06:21

@lee.justin.m doesn’t work unfortunately

justinlee16:06:32

@pesterhazy new (require("url").URL)("") seems to work in node

pesterhazy17:06:49

so is that possible in ClojureScript?

pesterhazy17:06:51

cljs.user=> (print (-> (fn [] (new (.-URL (js/require "url")) "")) .toString))
function (){
return (new require("url").URL(""));
}

pesterhazy17:06:50

the generated code sets the parentheses in the wrong place

pesterhazy17:06:11

it should yield new (require("url").URL)(arg), not (new require("url").URL(arg))

justinlee17:06:34

that’s above my pay grade. i don’t know what guarantees js/require provides in cljs

pesterhazy17:06:04

In node, (js/require) is just a function, it could be any other fn

justinlee17:06:44

right. so i’m now thinking that the code generation for new is maybe not ideal:

(print (-> (fn [] (new (.-a (.-b (js-obj))) "arg")) .toString))
=>
function (){
return (new {}.b.a("arg"));
}
That’s not right, is it? Don’t think it actually has anything to do with js/require

pesterhazy17:06:03

Right, nothing to do with require

pesterhazy17:06:27

Simple repro:

(let [f (fn [] js/Date)] (new (f)))

dnolen17:06:12

right misunderstanding about ‘new’

dnolen17:06:34

Argument must be class

dnolen17:06:39

Not expression

pesterhazy17:06:52

... should generate new (f.call(null))(), not (new f.call(null)())

pesterhazy17:06:08

my misunderstanding?

dnolen17:06:20

Nothing but passing a type will work

pesterhazy17:06:20

In JS, new takes any value

dnolen17:06:31

Which has nothing to do with Clojure new

dnolen17:06:56

new is not a JS-ism

pesterhazy17:06:44

basically what you're saying is that CLJS's new is what works with both Java and Js?

dnolen17:06:59

No what works in Clojure

pesterhazy17:06:20

Clojure's new is just Java's new, right?

pesterhazy17:06:06

Wouldn't hurt to generate an extra set of parentheses around the first arg of (new) though, right?

pesterhazy17:06:02

Not a big deal, the work-around is simply (let [C (f)] (new C arg))

dnolen17:06:08

I’d lean towards more validation to avoid the confusion

justinlee17:06:17

its too bad the logs linked to in cljs-334 are down. anyway to get them?

dnolen17:06:08

We may have relaxed it for some reason can’t look at it now. But anyways how new works should be considered in light of how it works in Clojure