* feat: removed IIFE and added solution * feat: updated challenges seed, test and solution * style: removed semicolon * feat: updated seed and solution * feat: updated challenges seed and solution * feat: updated test, seed and solution * fix: added seed code to solution * fix: removed function and added solution * fix: removed makeClass function and fixed solution * style: removed excessive semicolons * Fixed spacing for note in instructions section * fix: removed assert messages and used const * fix: regex fails correctly now
2.7 KiB
2.7 KiB
id, title, challengeType
id | title | challengeType |
---|---|---|
587d7b8b367417b2b2512b53 | Use class Syntax to Define a Constructor Function | 1 |
Description
class
syntax is just a syntax, and not a full-fledged class based implementation of object oriented paradigm, unlike in languages like Java, or Python, or Ruby etc.
In ES5, we usually define a constructor function, and use the new
keyword to instantiate an object.
var SpaceShuttle = function(targetPlanet){The class syntax simply replaces the constructor function creation:
this.targetPlanet = targetPlanet;
}
var zeus = new SpaceShuttle('Jupiter');
class SpaceShuttle {Notice that the
constructor(targetPlanet){
this.targetPlanet = targetPlanet;
}
}
const zeus = new SpaceShuttle('Jupiter');
class
keyword declares a new function, and a constructor was added, which would be invoked when new
is called - to create a new object.Note
UpperCamelCase should be used by convention for ES6 class names, as in
SpaceShuttle
used above.
Instructions
class
keyword and write a proper constructor to create the Vegetable
class.
The Vegetable
lets you create a vegetable object, with a property name
, to be passed to constructor.
Tests
tests:
- text: <code>Vegetable</code> should be a <code>class</code> with a defined <code>constructor</code> method.
testString: assert(typeof Vegetable === 'function' && typeof Vegetable.constructor === 'function');
- text: <code>class</code> keyword should be used.
testString: assert(code.match(/class/g));
- text: <code>Vegetable</code> should be able to be instantiated.
testString: assert(() => {const a = new Vegetable("apple"); return typeof a === 'object';});
- text: <code>carrot.name</code> should return <code>carrot</code>.
testString: assert(carrot.name=='carrot');
Challenge Seed
/* Alter code below this line */
/* Alter code above this line */
const carrot = new Vegetable('carrot');
console.log(carrot.name); // => should be 'carrot'
Solution
class Vegetable {
constructor(name) {
this.name = name;
}
}
const carrot = new Vegetable('carrot');