ClojureScript: How to add method via prototype to JS Object?

↘锁芯ラ 提交于 2019-12-06 03:10:56

问题


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:


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"))


来源:https://stackoverflow.com/questions/12420003/clojurescript-how-to-add-method-via-prototype-to-js-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!