[Javascript] 15. 객체그리고... method this

Eden·2022년 7월 29일
0

Javascript

목록 보기
15/33
post-thumbnail

method

객체 프로퍼티로 할당 된 함수가 method다!

<script>
const dog = {
	name : 'coco',
    age : 7,
    cute : function() {
    	console.log('귀엽습니다')
    }
}

dog.cute();//호출//"귀엽습니다"
</script>

객체의 cute함수가 dog객체의 method인 것을 알 수 있다. 단축 구문으로도 작성 할수 있다.

<script>
const dog = {
	name : 'coco',
    age : 7,
    //이렇게 줄여쓸 수 있다.
    cute() {
    	console.log('귀엽습니다')
    }
}
</script>

function키워드를 생략하면 된다.

객체와 method 관계

<script>
const user = {
	name : 'Eden',
    age : 20,
    sayHello : function() {
    						    //이 부분 주목!
    	console.log(`Hello, I'm ${user.name}`);
    }
}
</script>

보통 user라는 객체의 name에 접근할때 user.name으로 접근하는 것이 맞지만

이 방식은 문제가 발생할 수 있다.

이럴 때 사용하는 것이 this라는 키워드다.

<script>
//this
const user = {
	name : 'Eden',
    age : 20,
    sayHello : function() {
    						    //이 부분 주목!!
    	console.log(`Hello, I'm ${this.name}`);
    }
}

user.sayHello();//를 호출하면 user가 sayHello method의 this가 된다.
//"Hello, I'm Mike"
</script>

문제 발생을 막기 위해 user.name대신 this.name로 지정해주고 user객체의 sayHello()를 호출해주면 user가 sayHello의 this가 되는 것이다.

이해를 위해 예제를 더 알아보도록 하자!

예제

<script>
let boy = {           |  let girl = {
	name : 'Mark',    | 	 name : 'Eden',
}                     |  }

sayHello : funtion() {
	console.log(`Hello, I'm ${this.name}`);
}
</script>

여기서 this는 아직 결정 되지 않았다.
어떻게 호출하느냐에 따라 달라지게 된다.

각각의 객체에 이 함수를 method로 넣어준다.

<script>
let boy = {           |  let girl = {
	name : 'Mark',    | 	 name : 'Eden',
    sayHello,         |		 sayHello,
}                     |  }

sayHello : funtion() {
	console.log(`Hello, I'm ${this.name}`);
}

boy.sayHello();//"I'm Mark"
girl.sayHello();//"I'm Eden"
</script>

this는 실행하는 시점 즉, runtime에 결정하게 된다.
sayHello()thisboy.sayHello()girl.sayHello().앞의 객체다.
그래서 boy의 this.는 Mark고, girl의 this는 Eden이 된 것이다.

중요한 것은 만약 저 함수를 화살표함수로 선언하였다면 동작이 전혀 달라지게 된다.

화살표 함수는 일반함수와는 다르게 자신만의 this를 가지지 않는다.
화살표 함수 내부에서 this를 사용하면, 그 this는 외부에서 값을 가져오게 된다.

아래 화살표 함수를 살펴보자.

<script>
let boy = {
	name : "Mark",
    sayHello : () => {
    	console.log(this); //전역객체
    }
}

boy.sayHello();// this! = boy
</script>

이렇게 화살표 함수로 method를 만들고 코드를 실행하면 this는 boy객체를 가리키지 않는다.
화살표 함수는 this를 가지고 있지 않기 때문에 여기서 this를 쓰면 전역객체를 가리키게 된다.

참고로 브라우저 환경에서 전역객체는 window이고 Node.js환경에서는 global이 된다.

결론적으로 객체의 method를 작성할 때는 화살표함수를 작성하지 않는 게 좋다.

this **

자바스크립트에서 this는 상당히 복잡하다🫠
대부분의 사람들이 어려워하기에 더 주의깊게 살펴보도록 하자...!
결론적으로 method에서는 객체명을 직접 써주는 것보다 this를 활용하는 것이 좋다.

이번 파트에서는 객체의 method와 method 작성시 this의 변화에 대해 알아보았다. method를 작성할 때 this를 사용해서 객체에 접근해야 한다면 화살표 함수는 이용하지 않는 것이 좋다.

profile
one part.

0개의 댓글