简体   繁体   English

ClojureScript:如何通过原型向JS对象添加方法?

[英]ClojureScript: How to add method via prototype to JS Object?

I'm trying to add some functionality to an existing JavaScript system. 我正在尝试为现有的JavaScript系统添加一些功能。 To be then used from JavaScript again (as opposed to within the ClojureScript namespace). 然后再次从JavaScript中使用(而不是在ClojureScript命名空间中)。 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. 我已经尝试搞乱extend-typedefprotocol ,以及export ,但似乎没有任何东西暴露我的foo功能。

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. 这可能是一个设计决定而ClojureScript在这里不适合我,但我只是想确保我没有忽略某些东西。

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

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

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