코딩앙마 자바스크립트 기초 강의 13. 객체 메소드 / 디스(method / this)
method : 객체 프로퍼티로 할당 된 함수
const superman = {
name : 'clark',
age : 33,
fly : function(){
console.log('날아갑니다.')
}
}
superman.fly(); // console에 '날아갑니다.'가 찍힘
> fly는 superman개체의 method
const superman = {
name : 'clark',
age : 33,
fly(){
console.log('날아갑니다.')
}
}
이렇게 function을 생략해 줄여서 쓸 수 있다.
+객체의 키와 프로퍼티는 : 를 사용해서 적는다. = 를 사용하면 에러가 남!
const user = {
name : 'Mike',
sayHello : function(){
console.log(`Hello, I'm ${user.name}`);
}
}
저 안에 객체의 name 프로퍼티가 들어가게 하고 싶으면 이렇게?
일 거라고 생각할 수 있지만 이렇게 적으면 문제가 발생할 수 있음
이럴 때는 this 키워드를 사용
const user = {
name : 'Mike',
sayHello : function(){
console.log(`Hello, I'm ${this.name}`);
}
}
이렇게 하면 user.sayHello();를 호출 하면 user가 ${this.name}의 this가 되서 작동함
만약 method를 화살표 함수로 선언했다면 동작이 달라지게 됨
let boy = {
name : 'Mike',
sayHello : () => {
console.log(this); // 전역객체
}
}
boy.sayHello(); // this != boy
화살표 함수는 일반 함수와는 달리 자신만의 this를 가지지 않음
화살표 함수 내부에서 this를 사용하면 외부에서 this를 가져옴
화살표 함수는 this를 가지고 있지 않기 때문에 this는 전역객체가 됨
전역객체
브라우저 환경 : window
Node js : global
tip)
method에서는 this를 사용하는 게 좋음
객체의 method를 작성할 때 this를 사용해야 한다면 화살표 함수를 이용하지 않는게 좋다!