Skip to content

Instantly share code, notes, and snippets.

@kironroy
Last active July 26, 2023 00:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kironroy/8ebb6c776c5b0c153b49ca4156a1536f to your computer and use it in GitHub Desktop.
Save kironroy/8ebb6c776c5b0c153b49ca4156a1536f to your computer and use it in GitHub Desktop.
Classes
class PersonCl {
constructor(fullName, birthYear) {
this.fullName = fullName;
this.birthYear = birthYear;
}
// all functions outside the constructor()
// will be on the prototype
// not on the object itself
// methods will be added to .prototype property
// instance methods
calcAge() {
console.log(2037 - this.birthYear);
}
greet() {
console.log(`Hey ${this.firstName}`);
}
get age() {
return ` ${this.fullName} is ${2037 - this.birthYear}`;
}
// set a prop that already exists
set fullName(name) {
console.log(name);
if (name.includes(' ')) this._fullName = name;
else alert(`${name} is not a full name!`);
}
get fullName() {
return this._fullName;
}
// static methods
static hey() {
console.log('Hey there 👋');
console.log(this);
}
}
const tess = new PersonCl('Tess McBride', 1981);
console.log(tess);
tess.calcAge();
console.log(tess.age);
// PersonCl.prototype.greet = function () {
// console.log(`Hey ${this.firstName}`);
// };
tess.greet();
const mikey = new PersonCl('Mikey tyson', 1965);
const account = {
owner: 'jonas',
movements: [200, 333, 45, 66],
get latest() {
return this.movements.at(-1);
},
set latest(mov) {
this.movements.push(mov);
},
};
// get -> get something
console.log(account.latest);
// set something
account.latest = 26.7;
console.log(account.movements);
PersonCl.hey();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment