javascript : prototype based language
메모리 절감을 위해 사용
객체가 공통적으로 사용하는 속성을 만드는것.
person이라고 하는 생성자함수에 공통적으로 사용할 sum이라는 method를 만듦.
Person.prototye.sum =
function Person(name, first, second, third){
this.name=name;
this.first=first;
this.second=second;
}
Person.prototype.sum = function(){
return 'prototype : '+(this.first+this.second);
}
var kim = new Person('kim', 10, 20);
kim.sum = function(){
return 'this : '+(this.first+this.second);
}
var lee = new Person('lee', 10, 10);
console.log("kim.sum()", kim.sum());
console.log("lee.sum()", lee.sum());
kim.sum()으로 함수가 호출되면 kim이라는 속성에 sum이 있는지 먼저 파악함.
lee.sum()으로 함수를 호출하면 먼저 lee에 sum이라는 속성이 있는지 먼저 파악한 뒤 없으면 lee는 생성자를 사용했으므로 Person에 sum이라는 속성이 있는지 찾게됨.
__prpto__
var superObj = {superVal : 'super'}
var subObj = {subVal : 'sub'}
subObj.__proto__ = superObj; //subObj에 원형값으로 superObj를 줌
console.log(`subObj.subVal =>`, subObj.subVal); //sub
console.log(`subObj.superval =>`, subObj.superVal); //super
console.log(superObj.subval); //undefined
subObj.superval = 'sub';
console.log(superObj.superVal); //super
//subObj에 __proto__로 지정된 superObj의 값을 변환한 것이 아님.
//객체의 property를 바꾸는 것이 객체를 바꾸는 것이 객체의 proto를 바꾸는 것은 아님
superObj 부모, subObj가 자식
var superObj = {superVal : 'super'}
//superObj를 부모로 하는 새로운 객체를 만들기로 했을 때 통상적인 방법
var subObj = Object.create(superObj);
subObj.subVal = 'sub';
//__proto__를 이용한 방법
var subObj = {subVal : 'sub'}
subObj.__proto__ = superObj;
출처 : 생활코딩
'javascript' 카테고리의 다른 글
Tree / Binary Search Tree (0) | 2022.02.26 |
---|---|
this (0) | 2022.02.16 |
closure (0) | 2022.02.02 |
Execute context (0) | 2022.02.02 |
callback (0) | 2022.02.01 |