Web/자바스크립트

6. 생성자 함수로 객체 찍어내기

vision333 2021. 5. 24. 21:52
728x90

프레임워크를 위한 JavaScript ES6 강좌

https://edu.goorm.io/lecture/19879/프레임워크를-위한-javascript-es6

 

직접 객체 생성하기 -> 코드가 중복될 때 불편함.

var kim = {
	name : '김철수',
    	class : 1,
    	printinfo : function(){
    		console.log(this.name + "은 " + this.class + "반 입니다.");
    	}
};

var hong = {
      name : '홍길동',
      class : 2,
      printinfo : function(){
          console.log(this.name + "은 " + this.class + "반 입니다.");
      }
};

 

따라서 생성자 틀(함수)을 만들자.

function StudentInfo (name, class){
      this.name = name;
      this.class = class;
      this.printInfo = function(){
          console.log(this.name + "은 " + this.class + "반 입니다.");
      }
}

 

생성자 함수를 통해 객체 만들기

var 객체 이름 = new 생성자함수(인자);

var student1 = new StudentInfo('kim', 1);
var student2 = new StudentInfo('hong', 2);

객체의 함수 사용 가능하다.

student1.printinfo();

 

** 함수도 하나의 객체로 변수안에 담아 쓸 수 있다.

728x90
반응형