0

[JS/ES6] Some questions about objects

I have two questions about the old/new (ES6) way to define objects. In old JS I can create a "class/prototype" like this: function myClass(property1, property2, ...) { this.property1 = property1; this.property2 = property2; ... ; } But how about calculations inside the class definition? Is it possible in JS? My idea would be something like this: function car(color, date) { var now = new Date().getFullYear(); this.color = color; this.date = date; this.age = now - this.date; } And how do I create an "empty" class/prototype in ES6? This doesn't work since it's an object definition: let car = { color, date } How do I create classes in ES6? Is it possible? Many thanks in advance. Pete ____________________ P.S.: Take a look at my code https://code.sololearn.com/WM2DM8HXHxkb/?ref=app

21st Mar 2019, 12:39 PM
Pete Wright
Pete Wright - avatar
6 Réponses
+ 1
You could define a method name9d aged after the constructor (and inside the class) like this: class Car { // constructor // method(arg) {} get age() { return NOW - this.date; } // ... } now mycar.age will return the age
22nd Mar 2019, 10:40 AM
Pytness
Pytness - avatar
+ 1
class Car { constructor(color, date) { this.color = color; thid.date = date; } method(arg) {} } let myCar = new Car('blue', 2000);
22nd Mar 2019, 9:52 AM
Pytness
Pytness - avatar
+ 1
Thanks, and what about the calculations? Taking my example: car.age = NOW - car.date Is something like this possible?
22nd Mar 2019, 10:36 AM
Pete Wright
Pete Wright - avatar
+ 1
Are the "class" and "get" keywords new to ES6? I am still going through the ES6 course, but right now I'm at lesson 4/10. Btw, it works: https://code.sololearn.com/WAA86StTPfHR/?ref=app Once again, many thanks Pytness 🙏
22nd Mar 2019, 11:25 AM
Pete Wright
Pete Wright - avatar
+ 1
Yes, you have the keyword 'set' too by the way
22nd Mar 2019, 11:30 AM
Pytness
Pytness - avatar
0
Many thanks! 🙏 I will try it out right now
22nd Mar 2019, 11:01 AM
Pete Wright
Pete Wright - avatar