JavaScript(12) - Prototype과 Class 피하기
JavaScript 관련 포스팅
- JavaScript(1) - async vs. defer
- JavaScript(2) - variable
- JavaScript(3) - operator
- JavaScript(4) - function
- JavaScript(5) - class vs. object
- JavaScript(6) - object
- JavaScript(7) - array
- JavaScript(8) - JSON
- JavaScript(9) - callback
- JavaScript(10) - promise
- JavaScript(11) - Regular expressions
- JavaScript(12) - Prototype과 Class 피하기
- JavaScript(13) - localStorage
이후에 다른 코드도 다시 보기 |
prototype과 class를 피하는 코드
new
와this
의 사용을 피할 수 있음function secretFactory() { const secret = "Favor composition over inheritance, `new` is considered harmful, and the end is near!" const spillTheBeans = () => console.log(secret) return { spillTheBeans } } const leaker = secretFactory() leaker.spillTheBeans()
Console
Favor composition over inheritance,
new
is considered harmful, and the end is near!- spillTheBeans를 object로 return하는 함수(secretFactory)를 만들게 되면, 함수의 내용에 직접적인 접근을 막을 수 있음
another example
function spyFactory(infiltrationTarget) {
return {
exfiltrate: infiltrationTarget.spillTheBeans
}
}
const blackHat = spyFactory(leaker)
blackHat.exfiltrate() // Favor composition over inheritance, (...)
console.log(blackHat.infiltrationTarget) // undefined (looks like we got away with it)
Console
Favor composition over inheritance,
new
is considered harmful, and the end is near!undefined
< 출처 >
Justen Robertson, “As a JS Developer, This Is What Keeps Me Up at Night”, Toptal, 2019, https://www.toptal.com/javascript/es6-class-chaos-keeps-js-developer-up.