Last active
July 26, 2023 00:06
-
-
Save kironroy/8ebb6c776c5b0c153b49ca4156a1536f to your computer and use it in GitHub Desktop.
Classes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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