Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can also use instanceof, example with basic polymorphism.</p> <p>First create a superclass (ball)</p> <pre><code>// superclass function Ball() { this.play = function() { alert("Ball throw"); }; } </code></pre> <p>and now for some subclasses (types of balls)</p> <pre><code>// subclass function Basketball() { this.play = function() { alert("basketball throw"); }; } // subclass function Soccerball() { this.play = function() { alert("soccer ball kick/throw"); console.debug("here"); }; } // subclass function Baseball() { this.play = function() { alert("strike 3 you're out"); console.debug("here"); }; } </code></pre> <p>Give them Ball functionality, aka set their superclass via prototype</p> <pre><code>// set subclass functionality Basketball.prototype = new Ball(); Soccerball.prototype = new Ball(); Baseball.prototype = new Ball(); </code></pre> <p>Some polymorphism (create a bunch of balls and play with them all, but play based on type)</p> <pre><code>var bunchOfBalls = [new Baseball(), new Soccerball(), new Basketball()]; for (var i = 0; i &lt; bunchOfBalls.length; i++) { bunchOfBalls[i].play(); } </code></pre> <p>Now write a function that takes a ball but only want to to work for specific type of balls (mimic function overloading, more or less)</p> <pre><code>//overloading dependent upon type function BasketbalOrBaseballOnlyPlay(aBall) { if (aBall instanceof Basketball) { //special basketball function } if (aBall instanceof Baseball) { //special baseball function } } </code></pre> <p>If aBall is a Basketball so <code>aBall = new Basketball();</code> then <code>aBall instanceof Basketball</code> would return true for Basketball and false for baseball but true for Ball.</p> <p>So <code>aBall instanceof Ball</code> would return true because a Basketball is a Ball. </p> <p><a href="http://jsfiddle.net/kLCPB/" rel="nofollow">See code live at <a href="http://jsfiddle.net/kLCPB/" rel="nofollow">http://jsfiddle.net/kLCPB/</a></a></p>
 

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