ES6μμ μΆκ°λ μλ‘μ΄ κ°μ²΄ μμ± λ°©μμΌλ‘ ν΄λμ€ κΈ°λ° κ°μ²΄μ§ν₯ μΈμ΄μ²λΌ μ¬μ©ν μ μκ² λ§λ€μ΄λ Ό νμμ΄λ€.
// ν΄λμ€ μ μΈλ¬Έ
class Student {
constructor(name) {
this.name = name;
}
}
// μΈμ€ν΄μ€λ₯Ό new μ°μ°μλ₯Ό μ¬μ©νμ¬ μμ±
const student = new Student("kim");
// ν΄λμ€ μμ νλ‘νΌν°λ₯Ό μ¬μ©ν μ μμ
console.log(student.name);
/*
ν΄λμ€ ννμ
const Student = class {
constructor(name) {
this.name = name;
}
}
*/
ν΄λμ€μ μμλ constructor (μμ±μ), νλ‘ν νμ λ©μλ, μ μ λ©μλλ‘ κ΅¬μ±λμ΄ μλ€.
𧩠ν΄λμ€ λ΄λΆ μμμ νΉμ§
class Student {
static name = "Lee";
static log() {
console.log(`μ μ λ©μλ κ²°κ³Ό = ${this.name}`);
}
constructor(name) {
this.name = name;
}
log() {
console.log(`νλ‘ν νμ
λ©μλ κ²°κ³Ό = ${this.name}`);
}
}
const student = new Student("Kim");
// κ²°κ³Ό : μ μ λ©μλ κ²°κ³Ό = Lee
Student.log();
// κ²°κ³Ό : νλ‘ν νμ
λ©μλ κ²°κ³Ό = Kim
student.log();
function Student(age) {
this.age = age;
}
Student.prototype.log = function() {
console.log(`νλ‘ν νμ
λ©μλ κ²°κ³Ό = ${this.age}`);
}
Student.age = 21;
Student.log = function() {
console.log(`μ μ λ©μλ κ²°κ³Ό = ${this.age}`);
}
const student = new Student(30);
// κ²°κ³Ό : μ μ λ©μλ κ²°κ³Ό = 21
Student.log();
// κ²°κ³Ό : νλ‘ν νμ
λ©μλ κ²°κ³Ό = 30
student.log();
𧩠μμ±μ ν¨μμ ν΄λμ€μ μ μ λ©μλμ νλ‘ν νμ λ©μλ μ°¨μ΄
𧩠public νλ
𧩠private νλ
class Sum {
// constructor λ°μμ νλ‘νΌν°λ λ©μλμ #μ λΆνμ£Όλ©΄ privateμ΄λ€.
#num1 = 10;
constructor(num2) {
this.num2 = num2;
}
add() {
// ν΄λμ€ λ΄λΆμμλ private νλ‘νΌν°λ₯Ό μ°Έμ‘°ν μ μλ€.
return this.#num1 + this.num2;
}
}
const sum = new Sum(5);
// κ²°κ³Ό : 15
console.log(sum.add());
// κ²°κ³Ό : 5
console.log(sum.num2);
// κ²°κ³Ό : Private field '#num1' must be declared in an enclosing class (μ°Έμ΄ λΆκ°)
console.log(sum.#num1);