β μλ°μ€ν¬ννΈμ ν΄λμ€
// κΈ°μ‘΄μ μμ±μ ν¨μ
function Person(name, age){
this.name = name;
this.age = age;
}
var seho = new Person('μΈνΈ', 30)
// ν΄λμ€
class Person{
// ν΄λμ€ λ‘μ§
constructor(name, age){
console.log('μμ± λμμ΅λλ€');
this.name = name;
this.age = age;
}
}
var seho = new Person('μΈνΈ', 30);
console.log(seho)
- μμ λ κ°μ μ½λλ κ°μ΅λλ€.
β νμ
μ€ν¬λ¦½νΈμ ν΄λμ€
- λ¬Έλ²μ μΈ μ°¨μ΄κ° μμ΅λλ€.
class Person {
name: string; // class μμμλ§ μ¬μ©νκ³ μΆμΌλ©΄ μμ private μ¬μ©
age: number; // κΈ°λ³Έμ μΌλ‘ public
readonly log: string // μ½κΈ°μ μ©
constructor(name: string, age: number){
this.name = name;
this.age = age;
}
}
β μ½κΈ° μ μ©
- ν΄λμ€ μμ±μ
readonly
ν€μλλ₯Ό μ¬μ©νλ©΄ μλμ κ°μ΄ μ κ·Όλ§ κ°λ₯ν©λλ€.
class Developer {
readonly name: string;
constructor(theName: string) {
this.name = theName;
}
}
let john = new Developer("John");
john.name = "John"; // error! name is readonly.
μ°Έκ³