JavaScript 프로토타입

John Jeong (토론 | 기여)님의 2016년 11월 24일 (목) 08:20 판 (→‎Object.prototype)

1 개념

JavaScript Prototype
자바스크립트 프로토타입
객체 생성시 객체 원형인 프로토타입을 이용하여 새로운 객체를 만듦
향후, 프로토타입을 통해 객체를 확장함
  • 자바스크립트 언어는 클래스를 지원하지 않음 (ES6부터는 지원함)

2 Object.prototype

  • 객체를 생성하면 Object.prototype 이 기본적으로 상속됨
  • 원형객체에 속성과 메쏘드를 할당함으로 객체를 생성할 때 생성된 모든 객체에 그 내용이 들어가게됨
function Person(name, age) {
    this.name = name;
    this.age = age;
}
Person.prototype.gender = "man"; // 생성자의 원형객체에 gender 속성을 할당
Person.prototype.print = function() { // 생성자의 원형객체에 print 메쏘드를 할당
    console.log(this.name);
    console.log(this.age);
    console.log(this.gender);
}

var person_a = new Person("jmnote", 35);
var person_b = new Person("john", 38);
person_a.print();
person_b.print();

3 Object.create

  • Object.create() 메쏘드를 통해 객체 상속을 할 수 있음
var a = {a: "john"}; // a -> Object.prototype -> null
console.log(a.a); // john
var b = Object.create(a); // b -> a -> Object.prototype -> null
console.log(b.a); // john
var c = Object.create(b); // c -> b -> a -> Object.prototype -> null
console.log(c.a); // john

4 프로토타입 체인

  • 프로토타입의 연속 상속 관계를 프로토타입 체인이라 함
  • 상속값을 참조 할 시 현재 객체에 존재하지 않을 경우 부모 값을 참조 함
var a = {a: 1};
console.log(a.a); // 1 
var b = Object.create(a);
b.a = 2;
console.log(b.a); // 2 (현재 객체에 속성 a가 존재함)
var c = Object.create(b);
console.log(c.a); // 2 (현재 객체에 속성 a가 존재하지 않아 부모 객체 값 참조)

5 같이 보기

6 참고 자료

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}