[JS] Static,Protected,Privateμ λν΄ μμ보기
μλ νμΈμ Fomaπ» μ λλ€!
μ€λλ λͺ¨λ μλ°μ€ν¬λ¦½νΈμμ λ°°μ΄ Static,Protected,Private μ λν΄ μ κ° μ΄ν΄ν κ²μ λ°νμΌλ‘
μ λ¦¬ν΄ λ³΄λ €κ³ ν©λλ€!
λ°λ‘ μμν κ²μ~
Static
Staticμ μ μ μ΄λΌλ μλ―Έλ₯Ό κ°μ§κ³ μμ΄, λ³νμ§ μλλ€λ λ»μ΄λ€.
μ΄κ²μ μ΄μ©νμ¬ μ μ λ©μλ, νλ‘νΌν°λ₯Ό λ§λ€ μ μλ€.
μ½κ² λ§νλ©΄ ν΄λμ€μμ 곡ν΅μ μΌλ‘ κ°μ§κ³ μλ λΆλΆμ΄λ κΈ°λ₯μ 미리 μ μν΄ λλ κ²μ΄λ€.
Static Property
class Person {
//λͺ¨λ μ¬λμ΄ λμΌνκ² κ°μ§κ³ μκ³ λ³νμ§ μλ κ°
static planet = "μ§κ΅¬"
}
//ν΄λμ€ μ체μμ λ°λ‘ μ½κΈ° κ°λ₯
console.log(Person.planet) //μ§κ΅¬
Static Method
class User {
constructor(name,createDate) {
this.name = name
this.createDate = createDate
}
//λͺ¨λ μ μ κ° λμΌνκ² κ°μ§κ³ μκ³ λ³νμ§ μλ κΈ°λ₯
static sayHi() {
console.log("Hi")
}
static compare(user1,user2) {
return user1.createDate - user2.createDate
}
}
//ν΄λμ€ μ체μμ νΈμΆκ°λ₯
User.sayHi() //Hi
let users = [
new User("Foma",new Date(2021,1,1)),
new User("Gran",new Date(2020,1,1)),
new User("Young",new Date(2022,1,1))
]
//μλμ κ°μ΄ μ μ λ©μλλ₯Ό νμ©ν μ μμ
console.log(users.sort(User.compare))
/*
[
User { name: 'Gran', createDate: 2020-02-01T06:00:00.000Z },
User { name: 'Foma', createDate: 2021-02-01T06:00:00.000Z },
User { name: 'Young', createDate: 2022-02-01T06:00:00.000Z }
]
*/
//μλ‘μ΄ ν΄λμ€λ₯Ό λ§λ€ λλ μ μ©ν¨
User.createTodayNewUser = function() {
return new this("Foma",new Date())
}
Protected
Protectedλ ν΄λμ€μ ν΄λμ€μ μμκΉμ§ νμ© κ°λ₯νκ² νλ ν€μλμ΄λ€.
μμ±νλ λ°©μμ μ΄λ¦ μμ '_'λ₯Ό λΆμ΄κ³ μμ±νλ€.
_waterAmount = 0
_plusWaterAmount1() {...}
νμ§λ§ JavaScript λ¬Έλ²μ μΌλ‘ μ§μ ν κ²μ μλκΈ° λλ¬Έμ λͺ¨λ νΈμΆμ΄ λλ€.
κ°μ ν μ¬νμ΄ μλλ©° νλ‘κ·Έλλ¨Έλ€ μ¬μ΄μμ μ½μμΌλ‘ '_'μ΄ μλ€λ©΄ μΈλΆ μ κ·Όμ΄ λΆκ°λ₯ νλ€κ³ μ¬κΈ΄λ€.
console.log(a._waterAmount) //0
a._plusWaterAmount1() //waterAmount + 1
console.log(a._waterAmount) //1
Private
Privateλ ν΄λμ€ λ΄λΆμμλ§ νμ© κ°λ₯νκ² νλ ν€μλμ΄λ€.
μμ±νλ λ°©μμ μ΄λ¦ μμ '#'μ λΆμ΄κ³ μμ±νλ€.
#waterAmount = 0
#plusWaterAmount1() { ... }
Protectedμλ λ€λ₯΄κ² Privateλ λ¬Έλ²μ μΌλ‘ κ°μ νκΈ° λλ¬Έμ μΈλΆμμ νΈμΆνκ² λλ©΄ Errorκ° λ°μνλ€.
a.#plusWaterAmount() //Error
console.log(a.#waterAmount) //Error
Reference
The Modern JavaScript Tutorial
We want to make this open-source project available for people all around the world. Help to translate the content of this tutorial to your language!
javascript.info