Note that there are some explanatory texts on larger screens.

plurals
  1. POJavascript constructors with parameters
    text
    copied!<p>In trying to understand javascript constructors, I have been looking at <a href="https://stackoverflow.com/questions/892595/javascript-prototypal-inheritance">this question</a>.</p> <p>It seemed to me that I understood it reasonably, but, ironically, when I tried to run similar code, it did not work for me at all.</p> <p>This is my code</p> <pre><code>function Car(name) { this.Name = name; this.Year = 1999; } Car.prototype.Drive = function() { document.write("My name is '" + this.Name + "' and my year is '" + this.Year + "'. &lt;br /&gt;"); }; SuperCar = function () { }; SuperCar.prototype = new Car(); function SuperCar(name) { Car.call(this, name); } var MyCar = new Car("mycar"); var MySuperCar = new SuperCar("my super car"); MyCar.Drive(); MySuperCar.Drive(); </code></pre> <p>First of all, this line</p> <pre><code>SuperCar = function () { }; </code></pre> <p>was necessary for it to run at all. If I leave it out, I the error "SuperCar is undefined" at this line.</p> <pre><code>SuperCar.prototype = new Car(); </code></pre> <p>I don't really understand why declaring SuperCar as an empty function was necessary.</p> <p>Secondly, when I do run the code I get this result</p> <pre><code>My name is 'mycar' and my year is '1999'. My name is 'undefined' and my year is '1999'. </code></pre> <p>Apparently, for MySuperCar, the SuperCar(name) function is never called, but the Car() is.</p> <p>Adding this line does not help</p> <pre><code>SuperCar.prototype.constructor = SuperCar; </code></pre> <p>Neither does this</p> <pre><code>SuperCar.prototype.constructor = function(name) { Car.call(this, name); }; </code></pre> <p>(I have been running the code inside a script-tag on IE 9 and Chrome 22)</p> <p>How should I properly define a SuperCar constructor taking a name parameter? Or, put it another way, how can I make the new SuperCar("my super car") call behave the way I expected (setting the name to "my super car")?</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