Skip to content

Latest commit

 

History

History
executable file
·
190 lines (154 loc) · 3.64 KB

8. arrow function.md

File metadata and controls

executable file
·
190 lines (154 loc) · 3.64 KB

8. Arrow Function

8-1. 소개

var a = function () {
  return new Date()
}
var b = function (a) {
  return a * a
}
var c = function (a, b) {
  return a + b
}
var d = function (a, b) {
  console.log( a * b )
}
let a = () => new Date()
let b = a => a * a
let c = (a, b) => a + b
let d = (a, b) => {
  console.log( a * b )
}

8-2. 상세

1) (매개변수) => { 본문 }

2) 매개변수가 하나뿐인 경우 괄호 생략 가능

3) 매개변수가 없을 경우엔 괄호 필수

4) 본문이 return [식 or 값] 뿐인 경우 { }return 키워드 생략 가능

5) 위 4) 에서 return할 값이 객체인 경우엔 괄호 필수

const f = () => {
  a: 1,
  b: 2
}

const f = () => ({
  a: 1,
  b: 2
})

// 관용적으로 명시적인 인자전달이 없을 경우 _ 로 () 를 대신하고 한다

const f = _ => ({
  a: 1,
  b: 2
})

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

  • arrow function은 함수스코프 를 생성한다. 다만, 실행컨텍스트 생성시 this 바인딩을 하지 않는다.
const obj = {
  a: function () {
    console.log(this)

    const b = () => {
      console.log(this)
    }

    b()
  }
}
obj.a()
const obj = {
  grades: [80, 90, 100],
  getTotal: function () {
    this.total = 0
    this.grades.forEach(function(v) {
      this.total += v  // 이 부분의 this 는 window이다. 
    })
  }
}
obj.getTotal()
console.log(obj.total)

// 해결1) 무엇을 this 로 쓸것인지 인자로 전달 
const obj = {
  grades: [80, 90, 100],
  getTotal: function () {
    this.total = 0
    this.grades.forEach(function(v) {
      this.total += v 
    }, this)  // 무엇을 this 로 쓸것인지 인자로 전달 
  }
}

// 해결2) 화살표 함수
const obj = {
  grades: [80, 90, 100],
  getTotal: function () {
    this.total = 0
    this.grades.forEach(v => {
      this.total += v 
    })  //
  }
}

7) 명시적 this 바인딩 ?

  • 화살표 함수의 경우 명시적 this binding이 안된다.
const a = () => {
  console.log(this) // 여기서 this 는 window 이고
}
a.call({a: 1}) // 여기서도 여전히 this는 window 이기 때문에 window 객체가 출력된다.
  • 본연으 기능은 한다 다만 this가 변경되지 않는 것 뿐이다.
const a = (...rest) => {
  console.log(this, rest)
}
a.call({a: 1}, 1, 2, 3)
a.apply([], [4, 5, 6])
const b = a.bind(null, 7, 8, 9, 10)
b()
const obj = {
  f() {
    const a = (...rest) => {
      console.log(this, rest)
    }
    a.call({a: 1}, 1, 2, 3)
    a.apply([], [4, 5, 6])
    const b = a.bind(null, 7, 8, 9, 10)
    b()
  }
}
obj.f()

8) 생성자함수로 ?

  • 화살표 함수의 경우 prototype 프로퍼티가 없다. -> 생성자로 쓸 수 없다.

  • argumnet, callee 값이 null 이 아니라 숨겨져있고, invoke해야만 값을 얻을 수 있다. 컨텍스트가 시키면 error를 발생시킨다.

    • 이는 해당 컨텍스트 일 때만 보여지는 값이므로, 해당 컨텍스트가 아닐 경우 명시적으로 에러를 발생시키도록 조치를 취한 것이다.
  • concise method 도 이와 동일하다.

const P = (name) => {
  this.name = name
}
const j = new P('재남')

console.dir(P)

9) 그밖에

  • 메소드로의 기능보다는 함수로서의 기능에 충실하다.
  • this 외에도 super, arguments, new.target 등을 바인딩하지 않는다.
const b = {
  name: '하하',
  bb() {
    return this.name
  }
  a: x => {
  	return this.name 
	}
}

b.bb(); //"하하"
b.a(); //"" 빈 문자열 
window.name //"" 이 있나보다. 
window.name = "바보" // "바보"