Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialJayaraman Thiyyadi
9,031 PointsDice challenge unable to use ES2015 Arrow function for constructor
Hi, I tried using the constructor function which worked perfectly but when i try to update it for ES2015 it throws error in console.
// works fine
function dice(sides) {
this.sides = sides;
this.roll = function(){
return Math.floor(Math.random() * this.sides) + 1;
}
}
// this is not working. i tried using let and var key words too.
const dice = sides => {
this.sides = sides;
this.roll = function(){
return Math.floor(Math.random() * this.sides) + 1;
}
}
const dice1 = new dice(6);
const dice2 = new dice(6);
console.log(`${dice1.roll()} ${dice2.roll()}`);
2 Answers
Andrey Misikhin
16,529 PointsIf you using ES2015 syntax for creating class, then you must use "class" and appropriate syntax. Arror functions doen't have direct relationship with class constructor. And the main feature of arror function, that it have not it own "this" context, "this" takes from parent, but in your case the parent is just a constant, that doesn't have context by itself.
// this is not working. i tried using let and var key words too.
class Dice {
constructor(sides) {
this.sides = sides;
}
roll() {
return Math.floor(Math.random() * this.sides) + 1;
}
}
const dice1 = new Dice(6);
const dice2 = new Dice(6);
console.log(`${dice1.roll()} ${dice2.roll()}`);
Paolo Scamardella
24,828 PointsThat's because in es6 you should be using the class keyword to create an object, which is the syntatic sugar for es5 function constructor. You cannot use a es6 arrow function as a function constructor.