Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>JavaScript is a classless language. Classes don't exist, but objects may inherit properties from each other by using prototypes. This means you are not limited to implementing inheritance in a class-like manner. Personally, I like to use a BackboneJS-inspired method (code requires UnderscoreJS):</p> <pre><code>var BaseObject = function(){}; //Create a function so that we may use the new operator. //There may be code in the constructor BaseObject.extend = function(obj) { //Add a static function to the BaseObject to extend it var base = this; //Save a reference for later //Create the constructor for the sub object. We need to extend it, so we can't use the base constructor. AFAIK, this is the only way to clone the base constructor, i.e. by creating a new function that calls it var SubObject = _.extend(function(){ base.apply(this, arguments); //Call base constructor }, this); SubObject.prototype= _.extend({}, this.prototype, obj); //Create new prototype that extends the super prototype, but does not overwrite it. return SubObject; //Return the new constructor + prototype }; </code></pre> <p>This allows you to do cool class-like stuff like this:</p> <pre><code>var Car = BaseObject.extend({ speed: 0, acceleration: 5, accelerate: function(){ this.speed += this.acceleration; } }); var RaceCar = Car.extend({ acceleration: 10, }); var car = new Car(); var raceCar = new RaceCar(); car.accelerate(); raceCar.accelerate(); if(raceCar.speed &gt; car.speed){ console.log('raceCar won'); }else{ console.log('car won'); } </code></pre> <p>For more information on inheritance in JavaScript, I strongly recommend reading JavaScript: The Good Parts by Douglas Crockford.</p> <p>Regarding your examples:</p> <p>The difference between 1 and 2 is minimal. For more information see <a href="https://stackoverflow.com/questions/9423693/javascript-function-definition-syntax">this question</a>. </p> <p>In 3, you are just returning an object literal. The new keyword only has influence on the this keyword within the function, which you are not using, and so using new has no effect. For more information, see <a href="https://stackoverflow.com/questions/1646698/what-is-the-new-keyword-in-javascript">this quesion</a></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.
 

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