JavaScript 프로토타입

Jmnote (토론 | 기여)님의 2016년 11월 23일 (수) 23:50 판 (→‎개념)

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 같이 보기

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