简体   繁体   English

从ClojureScript调用JavaScript对象属性作为构造函数

[英]Calling JavaScript object property as a constructor from ClojureScript

I am using a JavaScript library that exposes a constructor as a property of a global object. 我正在使用一个JavaScript库,它将构造函数公开为全局对象的属性。

In JavaScript, I can call the constructor like this. 在JavaScript中,我可以像这样调用构造函数。

var thing = new Library.Thing();

How do I call the constructor in ClojureScript? 如何在ClojureScript中调用构造函数? None of these work. 这些都不起作用。

; These all cause compiler errors
(new (.-Thing js/Library)) ; First arg to new must be a symbol
(new (.Thing js/Library))
(new .-Thing js/Library)
(new .Thing js/Library)
(new js/Library/Thing)     ; Invalid token: js/Library/Thing

; These all compile to different JS than I am looking for
((.-Thing js/Library).) ; Library.Thing.call(null, _SLASH_);
((.Thing js/Library).)  ; Library.Thing().call(null, _SLASH_);

It works fine if I use js* but that's cheating, right? 如果我使用js *它可以正常工作,但这是作弊,对吧?

(js* "new Library.Thing()")

What is the proper way to call a constructor function that is a property of another object? 调用作为另一个对象属性的构造函数的正确方法是什么?

If you look at http://himera.herokuapp.com/synonym.html you can find the specific syntax to instantiate objets in clojurescript. 如果你查看http://himera.herokuapp.com/synonym.html,你可以找到在clojurescript中实例化objets的特定语法。

I wrote this js mock library based in this documentation to make a test: 我在本文档中编写了这个js mock库来进行测试:

function Person(name) {
this.name = name;
}

Person.prototype.greet = function() {
return "Hello, " + this.name;
};


var f={
"hola":"hola juan",

Person:Person

};

var person=new f.Person("Juan");
alert(person.greet());

Then from clojurescript you have to use the dot syntax (but prefixing with "js/" your js global type): 然后从clojurescript你必须使用点语法(但前缀为“js /”你的js全局类型):

(let [Person (.-Person js/f)
        juan (Person. "Juan")
        ]
    (.log js/console  (.greet juan)))

I don't mention in this answer the :externs property of your cljsbuild compilation beacuse I understand that you are including your js script library directly in your html head document. 我在这个答案中没有提到:你的cljsbuild编译的externs属性,因为我知道你直接在你的html头文档中包含你的js脚本库。 So, if this line works for you (js* "new Library.Thing()") it'll mean that the js library is available from the cljs-js-compiled. 所以,如果这条线适合你(js* "new Library.Thing()")那就意味着js库可以从cljs-js编译中获得。
Anyway, I left an "alert" in the js mock library to check that the file is correctly loaded 无论如何,我在js模拟库中留下了一个“alert”来检查文件是否正确加载

I hope it works for you 我希望这个对你有用
Juan 胡安

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM