- 객체를 이용하면, 서로 연관된 변수와 함수를 하나의 카테고리로 정리, 관리하고, 접근, 사용할 수 있어서 편리하다.
<script> const MyMath = { PI:Math.PI, random:function(){ return Math.random(); }, floor:function(e){ return Math.floor(e); } // 객체에 소속되어있을 땐 메소드 } console.log(MyMath.PI); console.log(MyMath.random()); console.log(MyMath.floor(4.1)); </script>
this는 메소드가 속해있는 객체를 가르치도록 약속된 예약어이다.
-따라서, 객체의 이름이 변하더라도 해당 메소드가 그 객체에 '속해 있다' 라는 성질은 변함이 없으므로, 영향을 받지 않고 값을 출력해낼 수 있다.<script> var kim = { name : 'minjae', first : 10, second : 20, sum : function(f,s){ return f+s; } } console.log(kim.sum(kim.first , kim.second)) </script>
this를 사용하면 다음 코드를 값을 불러올 때 훨씬 편리하다.
<script> const kim = { name : 'minjae', first:10, second:20, sum : function() { return this.first+this.second; } } console.log(kim.sum()); </script>