String.prototype.startsWith 在 ClojureScript 中的实现

Implementation of String.prototype.startsWith in ClojureScript

我需要将此 Javascript 代码转换为 ClojureScript。我在使用 this 关键字时遇到了一些问题。

这是我的 JS:

if (!String.prototype.startsWith) {
  String.prototype.startsWith = function(searchString, position) {
    position = position || 0;
    return this.indexOf(searchString, position) === position;
  };
}

我在高级模式下使用 Google Closure 编译器时遇到 Object doesn't support property or method 'startsWith' 错误,因此我需要添加此代码。 (IE 11)

试试这个 ClojureScript 代码:

(when (not (.. js/String -prototype -startsWith))
  (set!
    (.. js/String -prototype -startsWith)
    (fn [searchString position]
      (set! position (or position 0))
      (= (this-as this (.indexOf this) searchString position) position))))

ClojureScript 已经有 clojure.string/starts-with?:

$ clj -Sdeps '{:deps {org.clojure/clojurescript {:mvn/version "RELEASE"}}}' -m cljs.main -re node
ClojureScript 1.10.520
cljs.user=> (require '[clojure.string :as str])
nil
cljs.user=> (str/starts-with? "foobar" "foo")
true

re-find也可以帮你找到。