2022.04.22

JavaScript 화살표함수와 this

화살표 함수

일반함수
const hello = function () {}
화살표함수
const hello() = {} => {}
// 화살표함수 is 익명함수
// 함수표현식(어딘가할당하고있기때문에)이기때문에 호이스팅 발생 안해요

화살표 함수가 왜 나왔을까??

  1. 간소화가능 (패턴3가지)

    1. return키워드로 먼저시작할때 중괄호와 return 생략가능
      반환할데이터 어떤것이든 쓸 수 있다(원시형, 참조형)

      const hello = () => {  
       return 'Hello'
      }
      
      const hello = () => 'Hello'
      console.log(hello())

      단, 객체타입은 const hello = () => {}
      객체리터럴 중괄호와 기존 코드블록과 겹치기 때문에 소괄호로 감싸준다

      const hello = () => ({})  
      console.log(hello()) //undefined
      
      function hello(a, b) {
      return {
         a: a,
         b: b
         //key:a와 value:a에 사용된 변수이름이 같으면
         a,
         b
         }
      }
      
      function hello(a, b) {
      return {a, b} 
      }
      
      const hello = (a, b) => ({a, b})
    2. const hello = () => {
       console.log('Hello')
      }
      //콘솔이라는 객체안에 로그라는 함수가 있는데 
      //콘솔이라는 객체를 통해 실행되는 함수를 '메소드'라부름
      const hello = () => console.log('Hello')
      hello()
    3. //매개변수가 하나일때 소괄호를 생략할 수 있다(두개이상일때는 소괄호 필수)
      function hello(hi) {
      return `Hello ${hi)`
      }
      const hello = (hi) => `Hello ${hi}`
      
      const hello = hi => `Hello ${hi}`
  1. this
    가장큰이유! 바로 this 때문에

    console.log(this) //Window ......
    윈도우객체는 전역개체(Global 어디서든지 접근가능한)이자 최상위 객체

    var sunny = 'SUNNY' // console창에 sunny쳐야 나옴
    전역변수

    런타임 runtime 브라우저가 동작하는. 실제로 뭔가 돌아가고있는환경
    스코프(scope): 유효하게 동작하는범위

일반 또는 화살표 함수에서 정의가 다르다

const user = {
  name: 'Sunny',
  age: 92,
  email: 'ababab@gmail.com',
  phone: '01011112222',
  // 객체데이터에 property(속성)=key+value
  //메소드 속성에 함수가 있어? 그러면 메소드라불러요
  getName: function () {
    return [user.name, user.age]
}

console.log(user.getName()) // ['Sunny', 92]

객체이름을 직접참조를 하면은 객체이름이 바뀔때마다
문제가 생기가 되기때문에 유연한 `this`로바꿔준다
const user = {
  name: 'Sunny',
  age: 92,
  getName: function () {
    return [this.name, this.age]
}
  • 일반 함수에서 this키워드는 호출되는 위치에서 정의됨
//일반함수 this는 호출할때 적용된다
const jessi = {
  name: 'Jessi',
  age: 35
}
console.log(user.getName.call(jessi))

const userA = {
  name: 'A',
  age: 92,
  getAge: function () {
    return this.age
  }
}

const userB = {
  name: 'B',
  age: 83,
  getAge: function () {
    return this.age
  }
}

console.log(userA.getAge) //92
console.log(userB.getAge) //83
//call, apply = 호출용
//call은 앞에기능을 빌려줘, 특정객체가 가지고있지 않은 기능을 빌려서 씀
console.log(userB.getAge.call(userA)) //92
console.log(userB.getAge.apply(userA)) //92
  • 화살표 함수에서 this키워드는 자신이 선언된 함수(렉시컬) 범위에서 정의된다
    콜백에서 this를 쓴다면 화살표 함수를
const userA = {
  isValid: true,
  age: 92,
  getAge: function () {
    setTimeout(function () {
      console.log(this.age)
    }, 1000)
  }
}
userA.getAge() // undefined seTimeout안에서 호출됐기때문에

const userA = {
  isValid: true,
  age: 92,
  getAge: function () {
    setTimeout( () => {
      console.log(this.age)
    }, 1000)
  }
}
userA.getAge() // 92
끄적...

함수
function hello() {
//무언가를 호출할때는 항상 흔적을 남긴다
//hello()를 호출할건데 return키워드가 없으면 undefined 나온다
//'hello'라는 문자데이터을 반환할건데 호출할곳에 흔적데이터로 남게된다
//이제 데이터로 출력만 하면 된다!
}
hello()`

+ Recent posts