"JavaScript 프로토타입"의 두 판 사이의 차이

27번째 줄: 27번째 줄:
person_a.print();
person_a.print();
person_b.print();
person_b.print();
</source>
==Object.create==
*Object.create() 메쏘드를 통해 객체 상속을 할 수 있음
<source lang="javascript">
var a = {a: "john"};
console.log(a.a);
var b = Object.create(a);
console.log(b.a);
var c = Object.create(b);
console.log(c.a);
</source>
</source>



2016년 11월 24일 (목) 00:04 판

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"};
console.log(a.a);
var b = Object.create(a);
console.log(b.a);
var c = Object.create(b);
console.log(c.a);

4 같이 보기

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