진스
상속, 프로토타입 (prototype) 본문
728x90
상속되는 속성과 메소드들은 각 객체가 아니라 객체의 생성자의 prototype이라는 속성에 정의
JavaScript에서는 객체 인스턴스와 프로토타입 간에 연결(많은 브라우저들이 생성자의 prototype 속성에서 파생된 __proto__ 속성으로 객체 인스턴스에 구현)이 구성되며 이 연결을 따라 프로토타입 체인을 타고 올라가며 속성과 메소드를 탐색
//두 사람의 공통부분을 따로 만들고 상위의 prototype이 될부분
const hero = {
job: '배우',
action() {
console.log('촬영중...');
},
signature:'어벤져스'
}
const ironMan = {
actor : '로버트 다우니 주니어',
alias: '아이언 맨',
family:true,
name : '토니 스타크',
}
const captainAmerica = {
actor : '크리스 에반스',
alias: '캡틴 아메리카',
name : '스티븐 로저스',
}
//1단 상속
let iron = ironMan.__proto__ = hero //두 사람의 공통부분은 상위의 개념(prototype)을 만들어
console.log(ironMan);
/* actor: "로버트 다우니 주니어"
alias: "아이언 맨"
family: true
name: "토니 스타크" <-----가지고있던 속성들
[[Prototype]]: Object <-----.__proto__로 상속받은것들
action: ƒ action()
job: "배우"
signature: "어벤져스"
[[Prototype]]: Object */
//1단 상속 밑에 2단상속
captainAmerica.__proto__ = ironMan
/* 상속은 계속 이어질수있음
1.ironMan 을 상위로 두면
family:true 을 상속 받을 수있다.
프로퍼티들은 현재의 captainAmerica 값을 사용하고 그외 없는
family:true 같은 속성은 상속받아서 쓸수있게 된다.
2. ironMan은 hero를 상속 받았으므로
captainAmerica.job == '배우' 를 얻을수 있다.
*/
/* 위 객체 순회 */
for (p in captainAmerica) { //프로토타입에서 정의한 내용들이 다나옴
console.log(p); //actor alias name family job action signature 다 나옴
}
/* 키 값 관련 메소드는 안나옴 */
console.log(Object.keys(captainAmerica)); // ['actor', 'alias', 'name']
console.log(Object.values(captainAmerica)); // ['크리스 에반스', '캡틴 아메리카', '스티븐 로저스']
for (p in captainAmerica) { //구분하고 싶다면
if (captainAmerica.hasOwnProperty(p)) {
console.log('o', p); // o actor o alias o name
} else {
console.log('x', p);// x family x job x action x signature
}
}
// 생성자함수를 이용하면
const Benz = function (color) {
this.color = color
}
//이렇게 하나씩 추천! constructor 자동 부여
Benz.prototype.wheels = 4
Benz.prototype.drive = function () {
console.log('busan');
}
Benz.prototype.navigation = 1
Benz.prototype.stop = function(){
console.log('seoul');
}
//한번에 객체로 넣어주면 대신
// Benz.prototype = {
// constructor:Bmw, // 명시적으로 constructor 넣어줘야 함
// wheels: 4,
// drive() {
// console.log('busan');
// },
// navigation: 1,
// stop() {
// console.log('seoul');
// }
// }
const glb280 = new Benz('white')
const glb250 = new Benz('black')
//외부에서 접근
const Benz = function (color) {
const c = color
}
const glb280 = new Benz("white")
glb280.color = "red" // {color: 'red'} 외부에서 변경가능
//클로저를 이용하여 접근차단?
const Benz = function (color) {
const c = color
this.getColor = function () {
console.log(c); //white 외부에서 접근못함
}
}
const glb280 = new Benz("white")
glb280.color = "yellow"
728x90
'JavaScript' 카테고리의 다른 글
논리 연산자 || / && / ?? / ?. (or, and, 옵셔널 체이닝,Nullish coalescing) (0) | 2022.06.02 |
---|---|
Class (0) | 2022.05.19 |
call, apply, bind (0) | 2022.05.19 |
구조분해 할당 , 나머지 매개변수 , 전개구문 (0) | 2022.05.18 |
Array Methods (0) | 2022.05.18 |
Comments