ClojureScript: How to add a prototype method to a JS object?

I am trying to add some features to an existing JavaScript system. To be used again with JavaScript (as opposed to the ClojureScript namespace). Perhaps this is not 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 another place in the code.

I tried messing around with extend-typeand defprotocolas well as with export, but nothing showed my foo function.

It may have been a design decision and ClojureScript will not work for me here, but I just wanted to make sure that I didn’t notice anything.

+5
source share
1 answer

This can be done like this:

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

.. sugar:

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

All Articles