JavaScript 기초(화살표 함수, method)

Sujeong K·2022년 6월 30일
0

JavaScript_basic

목록 보기
6/17

화살표 함수

let add = function(a, b){
    return a + b;
}
let add = (a, b) => {
  return a + b;
} // function 없애고 간단히 표현
let add = (a, b) => (
    a + b;
) 
// {return asdf} 은 (asdf)로 표현 가능
// return문 전에 여러 코드가 있을 때는 ()로 쓸 수 없음
let add = (a, b) => a + b;
// return문이 한 줄일 때는 화살표 오른쪽 괄호 생략 가능
let sayHello = name => `Hello, ${name}`;
// 인수가 하나일 때는 (name)에서 괄호 생략 가능

📌인수가 없는 경우는 ( ) 생략 불가능

let showError = () => {
    alert('error!');
}

method

객체 프로퍼티로 할당된 함수
(출처 코딩앙마)

객체와 method의 관계 => this

📌 method의 this는 해당 객체를 가리킴

const user = {
    name: 'Jane',
    age: 30,
    sayHello: function(){
        console.log(`Hello, I'm ${this.name}`);
    }
}
user.sayHello(); // Hello, I'm Jane
user.name = 'Bob'
user.sayHello(); // Hello, I'm Bob
  • sayHello라는 method의 this.name은 실행하는 시점(runtime)에 결정됨

화살표 함수 내부에서 this를 사용하면 그 this는 함수 외부의 this를 가져옴

const user = {
    name: 'Jane',
    age: 30,
    sayHello: () => {
        console.log(this);
    }
}
user.sayHello(); // window 객체 출력함
  • 브라우저 환경에서 전역객체 this는 window
    *Node.js에서는 global

📌 화살표 함수는 일반 함수와는 달리 자신만의 this를 가지지 않음
📌 객체의 method를 작성할 때는 화살표 함수가 아닌 함수 선언문으로 쓰기 (this 사용할 경우 문제 발생 가능성 큼)

profile
차근차근 천천히

0개의 댓글