반응형

프로토타입

프로토타입은 생성자 함수로 생성된 객체가 공통으로 가지는 공간입니다. 

 

생성자 함수 구성 예

function Student(name, korean, math, english, science) {
    this.name = name;
    this.korean = korean;
    this.math = math;
    this.english = english;
    this.science = science;
}

 

프로토타입으로 메서드 생성하기 예

function Student(name, korean, math, english, science) {
    this.name = name;
    this.korean = korean;
    this.math = math;
    this.english = english;
    this.science = science;
}

Student.prototype.getSum = function() {
    return this.korean + this.math + this.english + this.science;
};
Student.prototype.getAverage = function() {
    return this.getSum() / 4;
};
Student.prototype.toString = function() {
    return this.name + '\t' + this.getSum() + '\t' + this.getAverage();
};

var student = new Student('shiro', 98, 34, 65, 77);

console.log(student.getSum()); // 274
console.log(student.getAverage()); // 68.5
console.log(student.toString()); // shiro 274 68.5

메서드는 모두 프로토타입 안에 넣어줍니다. 프로토타입은 우리가 만드는 것이 아니라, 함수 안에 자동으로 만들어지는 arguments와 마찬가지로 자바스크립트의 모든 함수는 변수 prototype을 갖습니다. ( prototype은 객체입니다. )

 

생성자 함수를 사용한 객체 배열 생성하기 예

function Student(name, korean, math, english, science) {
    this.name = name;
    this.korean = korean;
    this.math = math;
    this.english = english;
    this.science = science;
}

Student.prototype.getSum = function() {
    return this.korean + this.math + this.english + this.science;
};
Student.prototype.getAverage = function() {
    return this.getSum() / 4;
};
Student.prototype.toString = function() {
    return this.name + '\t' + this.getSum() + '\t' + this.getAverage();
};

var output = '이름 \t 점수 \t 평균 \n';
var students = [];
students.push(new Student('shiro', 98, 34, 65, 77));
students.push(new Student('AAA', 32, 43, 55, 66));
students.push(new Student('BBB', 44, 32, 12, 12));

for(var i in students) {
    output += students[i].toString() + '\n';
}

console.log(output);
/*
이름    점수    평균 
shiro  274    68.5
AAA    196    49
BBB    100    25
*/

프로토타입을 사용하면 기존 객체에 추가로 메서드를 제공할 수 있습니다.

 

new 키워드

new키워드로 함수를 호출하면 객체를 위한 공간을 만들고 this키워드는 해당 공간을 의미하게 됩니다.

 

new 키워드 예

function Constructor(value) {
    this.value = value;
}

var constructor = new Constructor('New');

console.log(constructor.value); // New

코드를 실행하면 New를 출력합니다. 

 

new 키워드를 사용하지 않을 경우

function Constructor(value) {
    this.value = value;
}

var constructor = Constructor('New');

console.log(value); // New

위 코드처럼 new키워드를 사용하지 않고, 일반 console.log()에 value변수를 사용하면 정상적으로 실행됩니다.

위에서 언급했듯이 일반적으로 this키워드를 사용하면 window객체를 나타냅니다. 따라서 일반적으로 함수를 호출하듯이 new키워드를 사용하지 않으면, 함수를 실행하는 동안 window객체에 속성을 추가한 것이 되어버립니다. 따라서 위코드처럼 실행이 이루어집니다.

 

반응형

+ Recent posts