title: Chained JS calls and this in scala.js
body: <p>I just have started with Scala.js and try to get a simple d3.js statement to work:</p>
  
  <pre><code>d3.select("body").append("svg")
  </code></pre>
  
  <p>To get a minimal working version I have cloned the scala.js tutorial, added d3.js into the index-fastopt.html and added the following code in the ScalaJSExample.scala (borrowed from <a href="https://github.com/spaced/scala-js-d3" rel="nofollow">https://github.com/spaced/scala-js-d3</a>):</p>
  
  <pre><code>trait Selection extends js.Array[js.Any] {
    var append: js.Function1[String, Selection] = js.native
  }
  
  trait Base extends js.Object {
    def select(selector: String): Selection = js.native
  }
  
  object Global extends scalajs.js.GlobalScope {
    val d3: Base = js.native
  }
  
  object ScalaJSExample extends js.JSApp {
    import Global._
    def main(): Unit = { 
      d3.select("body").append("svg")
    }
  
  }
  </code></pre>
  
  <p>However this code fails with the error:</p>
  
  <pre><code>Uncaught TypeError: this.select is not a function
     _a.append @ d3.v3.min.js:3
  </code></pre>
  
  <p>The fastOpt version of the statement is:</p>
  
  <pre><code> (0, $g["d3"]["select"]("body")["append"])("svg")
  </code></pre>
  
  <p>For me it looks like <code>append</code> is called with a <code>this</code> that is not the selection and therefore the call within append fails.</p>
  
  <p>The following version of the code works but is pretty cumbersome and non d3 idiomatic as d3 relies a lot on method chaining:</p>
  
  <pre><code>trait Selection extends js.Array[js.Any] {
    var append: js.ThisFunction1[Selection, String, Selection] = js.native
  }
  
  trait Base extends js.Object {
    def select(selector: String): Selection = js.native
  }
  
  object Global extends scalajs.js.GlobalScope {
    val d3: Base = js.native
  }
  
  object ScalaJSExample extends js.JSApp {
    import Global._
    def main(): Unit = { 
      val sel = d3.select("body")
      sel.append(sel, "svg")
  }
  </code></pre>
  
  <p>Is there a better way to pass the selection as <code>this</code> to append which allows me to preserve the fluent interface style of d3? </p>