5

I'm trying to add some functionality to an existing JavaScript system. To be then used from JavaScript again (as opposed to within the ClojureScript namespace). Perhaps this isn't possible?

Here's a simplification of what I want to do:

// JavaScript
String.prototype.foo = function() {
  return "bar";
}

# CoffeeScript
String::foo = ->
  "bar"

I want to be able to run my script above, and then call it from elsewhere in the code.

I've tried messing with extend-type and defprotocol, along with export, but nothing seemed to expose my foo function.

It's possible that this was a design decision and ClojureScript isn't going to work for me here, but I just wanted to make sure I wasn't overlooking something.

1 Answer 1

12

It can be done like so:

(set! (.-foo (.-prototype js/String)) (fn [] "bar"))

Or you can use .. sugar:

(set! (.. js/String -prototype -foo) (fn [] "bar"))
Sign up to request clarification or add additional context in comments.

5 Comments

Tested and works. If only that were in some documentation somewhere. :)
Yes someone needs to put together a ClojureScript page for common JavaScript interop forms.
Can you explain what some of that does--the .. is confusing. Does that just bring you out of the namespace?
No it's just sugar for deep property access.
I came across appletree.or.kr/quick_reference_cards/Others/… which has some helpful interop and general cljs forms.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.