JavaScript 객체 지향 - constructor

김민재·2021년 7월 9일
0

constructor

  • 함수 앞에 'new'라는 키워드를 붙으면 일반적인 함수가 아닌 객체를 생성하는 생성자(constructor)함수가 된다

-Construct Function는 일반 함수를 객체로 만들어 주는 객체 생성자이다.
-Construct Function을 적용하면 앞에 "new" 키워드를 사용하여 실행할때 마다 객체가 양상된다.
-따라서 변수 지정 시 각각의 객체를 수정할 필요없이 Construct Function을 바꾸면 Construct Function을 사용하는 모든 객체를 일괄 수정할 수 있는 장점을 지닌다.
(코드의 재사용에 이점)

<script>
const k = {
  name : 'jae',
  first:10,
  second:20,
  third:30,
  sum : function() {
    return this.first+this.second+this.third;
  }
}
const l = {
  name : 'min',
  first:10,
  second:10,
  third:10,
  sum : function() {
    return this.first+this.second+this.third;
  }
}
console.log("k.sum()",k.sum());
console.log("l.sum()",l.sum());
</script>

이전엔 객체를 만들 때 마다 객체를 다시 정의해야했다. 하지만 Construct Function을 만들면 New, 생성자 키워드를 사용함으로서 실행할떄마다 객체를 양산할 수 있다. 값을 바꾸면 모든 객체가 한번에 수정된다.

<script>
function Person(name, first, second, third){
  this.name = name;
  this.first = first;
  this.second = second;
  this.third = third;
  this.sum = function() {
    return this.first+this.second+this.third;
  }
}
const k = new Person('KIM',10,20,30);
const l = new Person('MIN',10,10,10);
</script>
  • 함수의 인자로 전달받은 값을 개체의 속성에 할당할 때 this를 사용한다.
  • 해당함수를 사용 할 때 new, 생성자 키워드로 새로운 객체를 만들고 인자를 넣어 사용한다.
profile
자기 신뢰의 힘을 믿고 실천하는 개발자가 되고자합니다.

0개의 댓글