× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Remember that not all javascript methods are chainable

James Jensen
Sep 18, 2014
<p>Sometimes we get used to the methods that return objects or promises that allow us to chain calls, or capture a variable after a call is complete:</p><pre><code class="language-javascript">var item = $('li').addClass('cool'); console.log(item); // same as $('li')</code></pre><p>In the above snippet, the console logs the result of `$('li')` because `addClass()` returns `this`. But other methods don't work the same way:</p><pre><code class="language-javascript">var subLayer = layer.getSubLayer(0).setInteraction(true); console.log(subLayer); // undefined</code></pre><p>Even though `getSubLayer(0)` returned a value, `setInteraction()` did not, so nothing was returned by the overall expression. Instead, we need to capture the result first, and call `setInteraction()` in its own statement.</p><pre><code class="language-javascript">var subLayer = layer.getSubLayer(0); subLayer.setInteraction(true); console.log(subLayer); // shows the subLayer object</code></pre>
comments powered by Disqus