* 자바스크립트(JavaScript) 생성자 함수(constructor)

- new 키워드로 객체를 생성할 수 있는 함수




1. 생성자 함수 개요

- 생성자 함수의 이름은 일반적으로 대문자로 시작

- 생성자 함수  안에서 this 키워드로 생성자 함수로 생성될 객체의 속성을 지정

- 생성자 함수 안에 메서드 생성 가능


<!-- constructor.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>constructor</title>
<script type="text/javascript">
	function Student(name, kor, math, eng, sci) {
		this.name = name;
		this.kor = kor;
		this.math = math;
		this.eng = eng;
		this.sci = sci;
		
		this.getSum = function() {
			return this.kor + this.math + this.eng + this.sci;
		};
		
		this.getAverage = function() {
			return this.getSum() / 4;
		};
		
		this.toString = function() {
			return this.name + ' ---------- ' + this.getSum() + ' ---------- ' + this.getAverage();
		};
	}
	
	var students = [];
	students.push(new Student('student1', 99, 99, 99, 99));
	students.push(new Student('student2', 88, 88, 88, 88));
	students.push(new Student('student3', 77, 77, 77, 77));
	students.push(new Student('student4', 66, 66, 66, 66));
	students.push(new Student('student5', 55, 55, 55, 55));
	students.push(new Student('student6', 44, 44, 44, 44));

	var output = 'name ---------- sum ---------- avg\n';
	for (var i in students) {
		output += students[i].toString() + '\n';
	}
	
	alert(output);
</script>
</head>
<body>
</body>
</html>

<!-- 
	▶ var st = new Student();
	- 생성자 함수(constructor) : new 키워드로 객체를 생성하는 Student() 함수
	- 객체(object) 또는 인스턴스(instance) : Student 생성자 함수로 만든 객체 st
 -->



1.1. instanceof 키워드

- 해당 객체가 어떠한 생성자 함수로 생성됐는지 확인할 때 사용


<!-- constructor2.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>constructor2</title>
<script type="text/javascript">
	function Student(name, kor, math, eng, sci) {
		this.name = name;
		this.kor = kor;
		this.math = math;
		this.eng = eng;
		this.sci = sci;
	}
	
	var st = new Student('Gz', 99, 88, 77, 66);
	
	alert(st instanceof Student); // true
	alert(st instanceof Number); // false
	alert(st instanceof String); // false
	alert(st instanceof Boolean); // false
</script>
</head>
<body>
</body>
</html>




2. 프로토타입(prototype)

- 객체에 같은 메서드로인해 메모리 낭비를 해결하기 위해 프로토타입 공간을 사용

- 프로토타입 : 생성자 함수로 생성된 객체가 공통으로 가지는 공간, 객체이며, 모든 함수는 prototype을 갖음

- 생성자 함수로 객체를 만들 때는 내부에 속성만 넣고, 메서드는 모두 프로토타입안에 넣음


<!-- constructor3.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>constructor3</title>
<script type="text/javascript">
	function Student(name, kor, math, eng, sci) {
		this.name = name;
		this.kor = kor;
		this.math = math;
		this.eng = eng;
		this.sci = sci;
	}
	
	Student.prototype.getSum = function() {
		return this.kor + this.math + this.eng + this.sci;
	}
	
	Student.prototype.getAverage = function() {
		return this.getSum() / 4;
	}
	
	Student.prototype.toString = function() {
		return this.name + ' ---------- ' + this.getSum() + ' ---------- ' + this.getAverage();
	}
	
	var students = [];
	students.push(new Student('student1', 99, 99, 99, 99));
	students.push(new Student('student2', 88, 88, 88, 88));
	students.push(new Student('student3', 77, 77, 77, 77));
	students.push(new Student('student4', 66, 66, 66, 66));
	students.push(new Student('student5', 55, 55, 55, 55));
	students.push(new Student('student6', 44, 44, 44, 44));

	var output = 'name ---------- sum ---------- avg\n';
	for (var i in students) {
		output += students[i].toString() + '\n';
	}
	
	alert(output);
</script>
</head>
<body>
</body>
</html>




3. 캡슐화

- 잘못 사용될 수 있는 객체의 특정 부분을 사용자가 사용할 수 없게 클로저를 활용하여 막는 기술

- 게터(getter) : getXX() 형태의 메서드

- 세터(setter) : setXX() 형태의 메서드


<!-- constructor4.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>constructor4</title>
<script type="text/javascript">
	function Rectangle(w, h) {
		var width = w;
		var height = h;

		this.getWidth = function() {
			return w;
		};
		
		this.getHeight = function() {
			return h;
		};
		
		this.setWidth = function(w) {
			if (w < 0) {
				throw '길이는 음수일 수 없습니다.';
			} else {
				width = w;
			} // if - else
		};
		
		this.setHeight = function(h) {
			if (w < 0) {
				throw '길이는 음수일 수 없습니다.';
			} else {
				height = h;
			} // if - else
		};
		
	} // Rectangle
	
	Rectangle.prototype.getArea = function() {
		return this.getWidth() * this.getHeight();
	};

	var rectangle = new Rectangle(5, 7);
	rectangle.setWidth(-2);

	alert('Area : ' + rectangle.getArea());
</script>
</head>
<body>
</body>
</html>




4. 상속

- 기존의 생성자 함수나 객체를 기반으로 새로운 생성자 함수나 객체를 쉽게 만드는 것

- 상속으로 새로 만들어지는 객체에는 기존 객체의 특성이 모두 있음


<!-- constructor5.html --> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>constructor5</title> <script type="text/javascript"> function Rectangle(w, h) { ... 생략 ... alert('Area : ' + rectangle.getArea()); </script> <script type="text/javascript"> function Square(length) { this.base = Rectangle; //Rectangle 객체의 속성을 Square 객체에 추가 this.base(length, length); } // Ractangle 객체의 프로토타입이 가진 속성 또는 메서드를 Square 객체의 프로토타입의 복사 Square.prototype = Rectangle.prototype; // square 객체의 프로토타입의 생성자 함수를 재정의 Square.prototype.constructor = Square; var rectangle = new Rectangle(5, 7); var square = new Square(5); alert(square instanceof Rectangle); // 상속 확인 true 이면 상속 alert(rectangle.getArea() + ' : ' + square.getArea()); </script> </head> <body> </body> </html>


+ Recent posts