04- JS 객체를 생성하는 방법

thomasKim·2023년 8월 13일

JAVASCRIPT 

목록 보기
3/3

01. 객체 리터럴을 사용한다.

<script>
	const obj1 = {name:'tom', age:10};
<script>
<script>
  const user1 = {name:'철수', age:30, job:'teacher'};
  const user2 = {name: '민수',age:10, job:null};
  const user3 = {name:'영희', age:40, job:'CEO'};
</script>

👆 이렇게 비슷한 형태의 객체들을 여러개 만들어 내고 싶을때,
하나씩 선언할 필요없게끔 틀을 만들어서 찍어내자. => 생성자 함수 👇👇👇

02. 생성자 함수

내부적으로 this에 {}객체가 생성된다.
내부적으로 return this;가 되기때문에 생략해도 됨
.

<script>
  function UserMaker(name,age,job){
      this.name = name;
      this.age = age;
      this.job = job;
  }
  const a = new UserMaker('철수',30,'teacher);
</script>

생성자 함수 내에 메서드를 만든다면?

<script>
function Person(name,age){
      this.name = name;
      this.age = age;
      this.sayHello = function(){
          console.log(`hello i'm ${this.name}`);
      } 
    }
    const tom = new Person('tom', 17);
    tom.sayHello();
    const 민수 = new Person('민수', 33);
    민수.sayHello();
</script>

👆 여기서, 문제점은 tom객체, 민수객체에 같은 함수가 반복적으로 생성된다는 것이다.

이러한 메모리 낭비 문제를 막기위해서는, 프로토타입에 메서드를 등록해둘 수 있다.

👆 tom과 민수객체 내에, 함수가 직접적으로 들어있지 않음.

👆프로토타입에 sayHello라는 메서드가 들어있어서, 접근하여 사용할 수 있음.
✔ 메모리 낭비는 줄이면서, 각 객체들에서 접근/사용은 가능해짐.

03. 클래스

<script>
  class Student{
      //👇생성자 함수 constructor
      //new 키워드 사용시, 생성자 함수가 호출된다.
      constructor(name, grade){
          this.name = name;
          this.grade = grade;
      }

      //this사용할 필요없이 그냥 메서드 작성가능
      greet = function(){
          console.log(`hello, i'm ${this.name}`);
      };
  }

  const minsoo = new Student('minsoo', 3);
  const thomas = new Student('thomas', 5);
  console.log(minsoo);
  console.log(thomas);

  minsoo.greet();
  thomas.greet();
</script>

👇 결과


Static 키워드

<script>
  class Student{
      //👇생성자 함수 constructor
      //new 키워드 사용시, 생성자 함수가 호출된다.
      constructor(name, grade){
          this.name = name;
          this.grade = grade;
      }

      //this사용할 필요없이 그냥 메서드 작성가능
      static greet = function(){
          console.log(`hello, i'm ${this.name}`);
      };
  }

  const minsoo = new Student('minsoo', 3);
  const thomas = new Student('thomas', 5);

  console.log(minsoo);
  console.log(thomas);

  minsoo.greet();
  thomas.greet(); 
</script>

👇 결과

static 키워드를 적게되면,
인스턴스(클래스로 만들어낸 객체)단에서 사용할 수 없게됨. 클래스 단에서 접근가능.
(모든 인스턴스에 등록되지 않으니까 메모리 절약 가능)

minsoo.greet(); ❌ //인스턴스 단에서 사용불가
Student.greet();만 이용가능해진다. //클래스 단에서 사용가능

이때, greet메서드 내에있는 this.는 클래스자체 를 가리켜서.
hello, i'm Student 가 출력된다. 👈 이렇게 각각의 인스턴스를 참조할 수 없게되니까
인스턴스를 참조할 필요가 없는 메서드,속성만을 static으로 사용하는게 좋다.



참고. Object.create();

<script>
const parentObj = {value:'parent'};
const childObj = Object.create(parentObj);
</script>
![](https://velog.velcdn.com/images/yeonkn/post/9f9b6c5d-57ee-466f-88a9-14e60e4d5b77/image.png)

👆 parentObj를 부모로하는 자식객체가 생성되어 변수 childObj에 할당된다.

👆비어있는 객체를 프로토타입으로 하는, 새로운 객체를 만들면서 'p'라는 속성에 42라는 value값을 지정(추가)해줌

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Object/create (참고)

profile
thomasKim

0개의 댓글