Skip to content

Instantly share code, notes, and snippets.

@vxhviet
Last active August 3, 2023 12:32
Show Gist options
  • Save vxhviet/ae5a98e36a7fd8ff7e4e49a8f3f532fe to your computer and use it in GitHub Desktop.
Save vxhviet/ae5a98e36a7fd8ff7e4e49a8f3f532fe to your computer and use it in GitHub Desktop.

[JavaScript] - ES6 Classes

SOURCE

// 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

Getters and Setters

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);

Static methods

See code example in the ES6 classes section

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment