// syntactic sugar, behind the scene it's still prototypal inheritance/ delegation
// Class expression
// const PersonCl = class {} // behind the scene class is still a special type of function
// Class declaration
class PersonCl {
constructor(fullName, birthYear) {
this.fullName = fullName;
this.birthYear = birthYear;
}
// Instance methods
// Methods will be added to .prototype property
calcAge() {
console.log(2037 - this.birthYear);
}
greet() {
console.log(`Hey ${this.fullName}`);
}
get age() {
return 2037 - this.birthYear;
}
// Set a property that already exists
set fullName(name) {
if (name.includes(' ')) this._fullName = name;
else alert(`${name} is not a full name!`);
}
get fullName() {
return this._fullName;
}
// Static method
static hey() {
console.log('Hey there 👋');
console.log(this);
}
}
const jessica = new PersonCl('Jessica Davis', 1996);
console.log(jessica);
jessica.calcAge();
console.log(jessica.age);
console.log(jessica.__proto__ === PersonCl.prototype); // true
// Basically the same as this
// PersonCl.prototype.greet = function () {
// console.log(`Hey ${this.firstName}`);
// };
jessica.greet();
// 1. Classes are NOT hoisted (we can't use them before they are declared in the code)
// 2. Classes are first-class citizens
// 3. Classes are executed in strict mode
Code example in classes in the previous section
const account = {
owner: 'Jonas',
movements: [200, 530, 120, 300],
get latest() {
return this.movements.slice(-1).pop();
},
set latest(mov) {
this.movements.push(mov);
},
};
console.log(account.latest);
account.latest = 50;
console.log(account.movements);
See code example in the ES6 classes section