/ JAVASCRIPT

JavaScript(12) - Prototype과 Class 피하기

JavaScript 관련 포스팅

이후에 다른 코드도 다시 보기

prototype과 class를 피하는 코드

  • newthis의 사용을 피할 수 있음
      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.