在clojurescript中扩展js日期的协议

时间:2013-11-22 04:38:42

标签: protocols clojurescript

我知道您可以使用以下types来扩展

object, array, function, string, nil

(extend-type nil Functor
 (fmap
   ([_ _] nil)
   ([_ _ _] nil)))

我希望为原生日期对象做同样的事情。怎么做的?

也..还有我缺少的小写类型吗?

1 个答案:

答案 0 :(得分:4)

以下是如何扩展Date对象:

(defprotocol Functor
  (fmap [_]))

(extend-type js/Date
  Functor
  (fmap
    ([_] (.log js/console 42))))

(fmap (js/Date.))      ;; logs 42

小写类型列表(来自https://github.com/clojure/clojurescript/blob/202cfcf045cf86d3ab295cbf16a347569b652647/src/cljs/clojure/data.cljs):

  

nil,string,number,array,function,boolean,default

来自himera(http://himera.herokuapp.com/synonym.html):

;; In addition native JavaScript objects like
;; Function, Object, Array, Number, String
;; are never actually directly extended

;; For example say you'd like to use RegExps
;; as functions

(extend-type js/RegExp
  IFn
  (-invoke
   ([this s]
     (re-matches this s))))

(filter #"foo.*" ["foo" "bar" "foobar"])
;; => ("foo" "foobar")
;; This is precisely how callable collections
;; are implemented.