JS) arrow function

kangdari·2020년 3월 31일
0

arrow function

  • 기존의 함수 선언을 보다 직관적으로 표현 가능함.
const a = () => console.log('arrow func')
const a = _ => consol.log('arrow func') ( _ or $ 는 사용 가능 )

const a = x => console.log(x)

const a = (x, y) => console.log(x, y)
const a = (x, y) => {
    console.log(x, y)
}
// 객체를 즉시 반환하는경우 ()로 감싸줘야 함
const obj = (x) => ({ x });
  • 함수가 함수를 리턴하는 경우
const f = function(a) {
    return function(b) {
        return a * b
    }
}

const f1 = a => b => a * b

실행 컨텍스트 생성 시 this 바인딩을 하지 않음

arrow function은 함수 스코프를 생성함. 단, 실행 컨텍스트 생성 시 this 바인딩 x

const obj = {
    a () {
        console.log(this) // {a: ƒ}
        const b = () =>{
            console.log(this) // {a: ƒ}
        }
        b()
    },
}
obj.a()
  • 비교

forEach의 callback func의 this는 window를 가르키기 때문에 여기서의 total은
window.total이다. (전역 변수 total)

const obj = {
    grades : [80, 90, 100],
    getTotal : function () {
        this.total = 0 // this: obj
        this.grades.forEach(function(v) {
            this.total += v // this : window
        })
    }
    
    // 바인딩을 해주는 경우
    // callback func에서 this를 바인딩해주면 total은 obj.total를 가리킨다.
    getTotal : function () {
        this.total = 0 // this: obj
        this.grades.forEach(function(v) {
            this.total += v // this: obj
        }, this) // 
    }
    
}
obj.getTotal()

arrow Func에서는 this를 바인딩하지 않기 때문에 forEach의 callback Func의 this는 obj를 가르킨다.

const obj = {
    grades : [80, 90, 100],
    getTotal : function () {
        this.total = 0 // this: obj
        this.grades.forEach((v) => {
            this.total += v // this: obj
        })
    }
}
obj.getTotal()
  • arrow function의 명시적 바인딩 ???
const a = () => console.log(this)

a() // Window
a.call({}) // Window, 
  • 기존 function과 비교
const b = function() {
    console.log(this)
}
b() // Window
b({}) // {}
  • prototype 프로퍼티가 없음 => 생성자 함수로 사용할 수 없다.
  • arguments, callee -> hidden(숨겨짐), invoke해야 사용 가능

0개의 댓글