변수와 관련된 메소드를 하나의 객체로 그룹핑/카테고라이징해 객체들을 조립하듯 프로그램을 만드는 것. 이 때 객체는 독립성을 갖게 되고, 좋은 부품이 될 수 있다.
Javascript는 Prototype-based programming, 프로토타입 기반 프로그래밍에 속해 있는 언어이다.
객체는 서로 연관된 변수와 함수를 그룹핑한 그릇이라고 할 수 있다. 객체 내의 변수를 프로퍼티(property(속성)), 함수를(변수 안의 값이 함수일 때) 메소드(method)라고 부른다.
var person = {} // -> Object
person.name = 'egoing'; // -> property
person.introduce = function() { // -> method
return 'My name is ' + this.name;
}
document.write(person.introduce()); //' My name is egoing'
여기서는 객체를 만드는 과정이 분산되어 있으므로 객체를 정의할 때 값을 세팅하도록 코드를 바꿔보자.
var person = {
'name' : 'egoing',
'introduce' : function(){
return 'My name is ' + this.name;
}
}
document.write(person.introduce());
var person1 = {
'name' : 'egoing',
'introduce' : function(){
return 'My name is ' + this.name;
}
var person2 = {
'name' : 'leezche',
'introduce' : function(){
return 'My name is ' + this.name;
}
만일 이같은 객체들이 있다면 중복되는 내용이 생기며, 나중에 객체 안의 값들을 수정하거나 유지보수할 때 일일이 수정해야 할 수 있다. 이럴 때 객체의 구조를 재활용하려 사용하는 것이 생성자이다.
function Person(){}
var p0 = Person();
p0 // undefined
var p = new Person(); // -> 생성자를 통해 만든 객체
p // Person {}
var p = {} // -> 객체리터럴을 통해 만든 객체
여기서 Person()은 new가 앞에 붙었기 때문에 생성자가 되고, 빈 객체를 생성해 p에 반환한다. 이처럼 함수에 new를 붙이면 객체가 된다.
var p = new Person()
과 var p = {}
는 같다고 볼 수 있다.
function Person(name){
this.name = name;
this.introduce = function(){
return 'My name is '+this.name;
}
}
var p1 = new Person('egoing');
document.write(p1.introduce()+"<br />");
var p2 = new Person('leezche');
document.write(p2.introduce());
위의 person1
, person2
를 생성자함수를 통해 재정의해보았다. 여기선 생성자 내에서 이 객체의 프로퍼티를 정의하고 있다. 이러한 작업을 초기화(initialization)라고 한다. 이를 통해 중복이 줄고 코드의 재사용성이 높아졌다.
출처 : 생활코딩 - Javascript