Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If the return value of a function is an object that has a method, you can call that method immediately. Simple as that.</p> <p>Since you're returning <code>this</code>, you're returning the same object that the previous method was called on. That means you're returning an object with all the same methods.</p> <hr> <p>Think of it this way:</p> <pre><code>var f = { foo: function() { console.log("foo"); return b; } }; var b = { bar: function() { console.log("bar"); return f; } }; </code></pre> <p>Here we have two objects. </p> <ul> <li>The <code>f</code> object has a method called <code>foo</code> that returns the <code>b</code> object.</li> <li>The <code>b</code> object has a method called <code>bar</code> that returns the <code>f</code> object.</li> </ul> <p>Because of this, after calling <code>foo</code>, we can call <code>bar</code>, and vice versa.</p> <pre><code>f.foo().bar().foo().bar(); // etc </code></pre> <p>But because <code>f</code> doesn't have <code>bar</code> and <code>b</code> doesn't have <code>foo</code>, we can never call the same method twice.</p> <hr> <p>But what if we only had one object, that had both methods, and both methods always returned the same original object?</p> <pre><code>var fb = { foo: function() { console.log("foo"); return fb; }, bar: function() { console.log("bar"); return fb; } }; </code></pre> <p>Now we're always returning an object that has both the <code>foo</code> and <code>bar</code> methods, so we can call either method.</p> <pre><code>fb.foo().bar().bar().bar().foo().foo().bar(); </code></pre> <p>So now the only real difference is that we are returning <code>fb</code> instead of <code>this</code>, but it doesn't matter since they're the same object. The code above could do <code>return this;</code> and it would behave the same.</p> <p>It would matter if you wanted to create several instances of the object, but <strong><em>that's a question of object orientation techniques, not method chaining</em></strong>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload