JS prototype 활용

murkgom·2020년 12월 24일
0

prototype chaining

개념

  • 해당 객체에 property가 없을 경우, prototype에서 이를 탐색 & 반복(proto의 proto...)
const func1 = function() {
	this.a = 10;
  	this.b = 20;
}

const obj1 = new func1();

func1.prototype.b = 21;
func1.prototype.c = 30;

console.log(obj1.a);		//10
console.log(obj1.b);		//20. func1의 생성시 존재하므로 chaining 미발생
console.log(obj1.c);		//30. func1의 생성자에 없으므로 chaining 발생, prototype에서 찾아 리턴

주의점

  • proto의 depth가 많을 경우, 많은 chaining이 발생
  • hasOwnProperty 메서드를 통해 방지 필요
if (obj1.hasOwnProperty()) {
	console.log(obj1.c);
}

prototype 활용

function Person(name, age) {
    this.name = name;
    this.age = age;
}

Person.prototype = {
    showInformation: function() {
        console.log(`${this.name}의 나이는 ${this.age}입니다.`);
    }
};

const kim = new Person('kim', 30);
const cu = new Person('cu', 28);
kim.showInformation();		//kim의 나이는 30입니다.
cu.showInformation();		//cu의 나이는 28입니다.

기타 : 상속

const a = {v: 1};
const b = Object.create(a);
const c = Object.create(b);

console.log(b.v);		//1
console.log(c.v);		//1

0개의 댓글