진취적 삶
19 프로토타입 본문
js는 클래스 기반 프로그램보다 더 효율적이며 강력한 프로토타입 기반의 객체지향 프로그래밍 언어
문법적 설탕 (syntatic sugar) : 사람이 이해하고 표현하기 쉽게 디자인된 프로그래밍 언어 문법
19.1 객체 지향 프로그래밍
객체의 집합으로 프로그램을 표현하려는 프로그래밍 패러다임
다양한 속성 중에서 프로그램에 필요한 속성만 간추려 내어 표현하는것을 추상화 라고 한다.
속성을 통해 여러개의 값을 하나의 단위로 구성한 복합적인 자료구조를 객체라고 함
객체는 상태 데이터와 동작을 하나의 논리적인 단위로 묶은 복합적인 자료구조
객체의 상태 = 프로퍼티
객체의 동작 = 메서드
19.2 상속과 프로토타입
상속은 어떤 객체의 프로퍼티 또는 메서드를 다른 객체가 상속받아 그대로 사용할수 있는것
상속을 통해 불필요한 중복을 없앤다
js 는 프로토타입을 기반으로 상속을 구현한다 .
function Circle(radius) {
this.radius = radius;
}
//Circle 생성자 함수가 생성한 모든 인스턴스가 getArea 메서드를 공유해서
//사용할 수 있도록 프로토타입에 추가한다.
// 프로토 타입은 Circle 생성자 함수의 prototype 프로퍼티에 바인딩 되어있다.
Circle.prototype.getArea = function () {
return Math.PI * this.radius ** 2;
};
const circle1 = new Circle(1);
const circle2 = new Circle(2);
console.log(circle1.getArea === circle2.getArea);
console.log(circle1.getArea());
console.log(circle2.getArea());
19.3 프로토타입 객체
프로토타입 객체는 객체지향 프로그래밍의 근간을 이루는 객체 간 상속을 구현하기 위해 사용
모든객체는 prototype 이라는 내부 슬롯을 가지며 이 내부슬롯의 값은 프로토타입의 참조이다 .
객체가 생성될때 객체 생성 방식에 따라 프로토타입이 결정되고 prototype에 저장된다.
모든 객체는 하나의 프로토타입을 갖는다 .
proto 접근자 프로퍼티를 통해 자신의 프로토타입 , 자신의 prototype 내부 슬롯이 가리키는 프로토타입에 간접적으로 접근할수 있다.
프로토타입은 자신의 constructor 프로퍼티를 통해 생성자 함수에 접근할수 있고,
생성자 함수는 자신의 prototype 프로퍼티를 통해 프로토타입에 접근할수 있다.
19.3.1 proto 접근자 프로퍼티
모든 객체는 proto 접근자 프로퍼티를 통해 자신의 프로토 타입 즉 [[prototype]] 내부 슬롯에 간접적으로 접근할수 있다 .
- proto 는 접근자 프로퍼티이다. 내부 슬롯은 프로퍼티가 아니다 . js는 원칙적으로 일부 내부 슬롯과 내부 메서드에 간접적으로 접근할수 있는 수단을 제공한다 접근자 프로퍼티는 자체적으로 값을 갖지 않고 다른 데이터 프로퍼티의 값을 읽거나 저장할때 사용하는 접근자 함수 , 즉 get set 프로퍼티 어트리뷰트로 구성된 프로퍼티이다 .
- proto 접근자 프로퍼티는 상속을 통해 사용 proto 는 객체가 직접 소유하는 프로퍼티가 아니라 Object.prototype 의 프로퍼티이다 . 모든 객체는 상속을 통해 Object.prototype.proto 접근자 프로퍼티를 사용할수 있다.
const person = { name: "suha" };
// person 객체는 __proto__ 프로퍼티를 소유하지 않는다 .
console.log(person.hasOwnProperty("__proto__")); //false
//__proto__ 는 모든 객체의 프로토 타입 객체인 Object.prototype 의 접근자 프로퍼티
console.log(Object.getOwnPropertyDescriptor(Object.prototype, "__proto__"));
//모든 객체는 object. prototype 의 접근자 프로퍼티 __proto__를 상속받아 사용할수 있다.
console.log({}.__proto__ === Object.prototype);
Object.prototpye : 모든 객체는 프로토타입의 계층 구조인 프로토타입 체인에 묶여있다. js 엔진은 객체의 프로퍼티에 접근하려고 할때 해당 객체에 접근하려는 프로퍼티가 없다면 proto 접근자 프로퍼티가 가리키는 참조를 따라 자신의 부모 역할을 하는 프로토타입의 프로퍼티를 순자적으로 검색한다 .
프로토 타입의 최상위 객체는 Object.prototype 이며 이 객체의 프로퍼티와 메서드는 모든 객체에 상속된다 .
- proto 접근자 프로퍼티를 통해 프로토타입에 접근하는 이유 프로토타입 체인은 단방향 링크드 리스트로 구현되어야 한다. 순환 참조하는 프로토타입 체인이 만들어지면 체인 종점이 존재하지 않기때문에 프로토타입 체인에서 프로토타입 검색할때 무한 루프에 빠진다. 따라서 무조건적으로 프로토타입을 교체할수 없도록 proto 접근자 프로퍼티를 통해서 프로토타입에 접근하고 교체하도록 한다 .
- proto 코드 내에서 직접 사용은 권장 안함 모든 객체가 proto 접근자 프로퍼티를 사용할수 있는것은 아니다.
//obj 는 프로토타입 체인의 종점 따라서 Object . __proto__ 를 상속받을수 없다.
const obj = Object.create(null);
//obj는 Object . __proto__ 를 상속받을수 없다.
console.log(obj.__proto__); //undefined
//따라서 Object.getPrototypeOf 사용하는 편이 좋다
console.log(Object.getPrototypeOf(obj)); //null
19.3.2 함수 객체의 prototype 프로퍼티
함수 객체만이 소유하는 prototype 프로퍼티는 생성자 함수가 생성할 인스턴스의 프로토 타입을 가리킨다 .
// 함수 객체는 prototype 프로퍼티 소유
(function () {}.hasOwnProperty("prototype")); //true
// 일반 객체는 prototype 프로퍼티를 소유하지 않는다
({}.hasOwnProperty("prototype")); //fasle
//화살표 함수는 non-constructor
const Person = (name) => {
this.name = name;
};
// non-constructor 는 prototype 프로퍼티를 소유하지 않는다
console.log(Person.hasOwnProperty("prototype"));
//non-constructor 는 프로토타입을 생성하지 않는다 .
console.log(Person.prototype);
const obj = {
foo() {},
};
// non-constructor 는 prototype 프로퍼티를 소유하지 않는다
console.log(obj.foo.hasOwnProperty("prototype"));
//non-constructor 는 프로토타입을 생성하지 않는다 .
console.log(obj.foo.prototype);
모든 객체가 가지고있는 proto 접근자 프로퍼티와 함수 객체만이 가지고 있는 prototype 프로퍼티는 결국 동일한 프로토타입을 가리킨다 .
구분 소유 값 사용 주체 사용 목적
proto | 모든 객체 | 프로토타입의 | ||
참조 | 모든 객체 | 객체가 자신의 프로토 타입에 접근 또는 교체하기 위해 사용 | ||
prototype | constructor | 프로토타입의 | ||
참조 | 생성자 함수 | 생성자 함수가 자신이 생성할 객체의 프로토타입 할당하기 위해 사용 |
function Person(name) {
this.name = name;
}
const me = new Person("suha");
// Person.prototype 과 me.__proto__ 는 동일한 프로토 타입을 가르킨다
console.log(Person.prototype === me.__proto__); //true
19.3.3 프로토 타입의 constructor 프로퍼티와 생성자 함수
모든 프로토타입은 constructor 프로퍼티를 갖는다 .
이 constructor 프로퍼티는 prototype 프로퍼티로 자신을 참조하고 있는 생성자 함수를 가리킨다.
function Person(name) {
this.name = name;
}
const me = new Person("suha");
//me 객체의 생성자 함수는 Person //true
console.log(me.constructor === Person);
19.4 리터럴 표기법에 의해 생성된 객체의 생성자 함수와 프로토 타입
const obj = {};
//true
console.log(obj.constructor === Object);
생성자 함수로 생성한 객체가 아니라 객체 리터럴에 의해 생성된 객체
하지만 obj 객체는 Object 생성자 함수와 constructor 프로퍼티로 연결되어 있다.
리터럴 표기법에 의해 생성된 객체도 가상적인 생성자 함수를 갖는다.
프로토타입과 생성자 함수는 단독으로 존재할수 없고 언제나 쌍으로 존재한다.
19.5 프로토타입의 생성 시점
프로토타입은 생성자 함수가 생성되는 시점에 더불어 생성된다.
19.5.1. 사용자 정의 생성자 함수와 프로토타입 생성 시점
생성자 함수로서 호출할수있는 함수 (화살표 함수 말고)
constructor 는 함수 정의가 평가되어 함수 객체를 생성하는 시점에 프로토타입도 더불어 생성된다.
console.log(Person.prototype);;
function Person(name) { // {constructor: f}
this.name = name;
}
const Person = name => {
this.name = name ;
}
console.log(Person.prototype); // undefined
함수 선언문은 런타임 이전에 js 엔진에 의해 먼저 실행된다. 생성자 함수는 먼저 평가되어
함수객체가 되며 프로토타입도 더불어 생성된다 .
생성된 함수의 prototype 프로퍼티에 바인딩 된다.
19.5.2 빌트인 생성자 함수와 프로토타입 생성 시점
Object, string,Number,Function 등 빌트인 생성자 함수도 일반 함수와 마찬가지로
빌트인 생성자 함수가 생성되는 시점에 프로토 타입이 생성된다.
객체가 생성되기 이전에 생성자 함수와 프로토타입은 이미 객체화 되어 존재한다.
생성자 함수 또는 리터럴 표기법으로 객체를 생성하면 프로토타입은 생성된 객체의
내부 슬롯에 할당된다.
19.6 객체 생성 방식과 프로토 타입의 결정
객체 생성방법
- 객체 리터럴
- Object 생성자 함수
- 생성자 함수
- Object .create 메서드
- 클래스
모든 생성은 추상 연산 OrdinaryObjectCreate 에 의해 생성된다.
프로토타입은 추상 연산 OrdinaryObjectCreate 에 전달되는 인수에 의해 결정된다.
19.6.1 객체 리터럴에 의한 생성된 객체의 프로토타입
객체 리터럴을 평가하여 객체를 생성항때 추상 연산 OrdinaryObjectCreate를 호출한다.
이때 전달되는 프로토 타입은 Object.prototype 이다 .
객체 리터럴에 의해 생성되는 객체의 프로토타입은 Object. prototype 이다 .
const obj = { x: 1 };
//객체 리터럴에 의해 생성된 obj 객체는 Object. prototype을 상속받는다
console.log(obj.constructor === Object);
console.log(obj.hasOwnProperty("x"));
19.6.2 Object 생성자 함수에 의해 생성된 객체의 프로토타임
Object 생성자 함수를 호출하면 OrdinaryObjectCreate 가 호출된다 .
OrdinaryObjectCreate 에 전달되는 프로토 타입은 Object.prototype 이다
const obj = new Object();
obj.x = 1;
//Object 생성자 함수에 의해 생성된 obj 객체는 Object.prototype을 상속받는다
console.log(obj.constructor === Object); //true
console.log(obj.hasOwnProperty("x")); //true
19.6.3 생성자 함수에 의해 생성된 객체의 프로토타임
new 연산자와 함께 생성자 함수를 호출하면 OrdinaryObjectCreate 가 호출된다 .
OrdinaryObjectCreate 에 전달되는 프로토 타입은 생성자 함수의 prototype 프로퍼티에 바인딩 되어 있는 객체다
프로토 타입은 객체이기에 프로퍼티를 추가/삭제할수 있다.
function Person(name) {
this.name = name;
}
//프로토타입 메서드
Person.prototype.sayHello = function () {
console.log(`hi my name is ${this.name}`);
};
const me = new Person("lee");
const you = new Person("kim");
me.sayHello();
you.sayHello();
19.7 프로토타입 체인
me 객체는 hasOwnProperty 를 호출할수 있다.
me 객체는 Person.prototype 뿐만 아니라 Object.prototype 도 상속받았다는것
js는 객체의 프로퍼티에 접근하려고 할때 해당 객체에 접근하려는 프로퍼티가 없다면
Prototype 내부 슬롯의 참조를 따라 자신의 부모역할을 하는 프로토 타입의 프로퍼티를 순차적으로 검색한다. 이를 프로토타입 체인이라한다.
function Person(name) {
this.name = name;
}
Person.prototype.sayHello = function () {
console.log(`hi my name is ${this.name}`);
};
const me = new Person("lee");
console.log(me.hasOwnProperty("name"));
프로토타입 체인은 상속과 프로퍼티 검색을 위한 메커니즘이라고 할수 있다.
식별자는 스코프 체인에서 검색한다.
me.hasOwnProperty('name')
스코프 체인에서 me 식별자를 검새하고 me 객체의 프로토타입 체인에서 hasOwnProperty 메서드 검색
스코프 체인과 프로토타입 체인은 서로 협력하여 식별자와 프로퍼티를 검색하는데 사용
19.8 오버라이딩과 프로퍼티 새도잉
const Person = (function () {
function Person(name) {
this.name = name;
}
Person.prototype.sayHello = function () {
console.log(`hi my name is ${this.name}`);
};
return Person;
})();
const me = new Person("suha");
me.sayHello = function () {
console.log(`my name is ${this.name}`);
};
me.sayHello();
프로토 타입이 소유한 프로퍼티를 프로토타입 프로퍼티
인스턴스가 소유한 프로퍼티를 인스턴스 프로퍼티
상속관계에 의해 프로퍼티가 가려지는 현상을 프로퍼티 새도잉이라 한다 .
오버라이딩 : 상위 클래스가 가지고 있는 메서드를 하위 클래스가 재정의하여 사용하는것
오버로딩 : 함수의 이름은 동일하지만 매겨변수의 타입또는 개수가 다른 메서드를 구현하고 매개변수에 의해 메서드를 구별하여 호출하는 방식
인스턴스 메서드를 삭제할경우 프로토타입 메서드가 아니라 인스턴스 메서드가 삭제된다.
프로토타입 프로퍼티를 변경 또는 삭제하려면 하위 객체를 통해 접근하는것이 아니라
프로토 타입에 직접 접근해야한다.
const Person = (function () {
function Person(name) {
this.name = name;
}
Person.prototype.sayHello = function () {
console.log(`hey my name is ${this.name}`);
};
return Person;
})();
const me = new Person("suha");
me.sayHello();
//프로토 타입 메서드 삭제
delete Person.prototype.sayHello;
me.sayHello();
19.9 프로토타입의 교체
프로토타입은 임의의 다른 객체로 변경 가능하다 .
객체간의 상속 관계를 동적으로 변경할수 있다.
19.9.1 생성자 함수에 의한 프로토 타입의 교체
const Person = (function () {
function Person(name) {
this.name = name;
}
//생성자 함수의 prototype 프로퍼티를 통해 프로토 타입을 교체
// 객체 리터럴 할당
Person.prototype = {
sayHello() {
console.log(`hi my name is ${this.name}`);
},
};
return Person;
})();
const me = new Person("suha");
프로토 타입으로 교체한 객체 리터럴에는 constructor 가 없다 .
constructor 프로퍼티는 js 엔진이 프로토 타입을 생성할 때 암묵적으로 추가한 프로퍼티이다.
me 객체의 생성자 함수를 검색하면 Person 이 아닌 Object가 나온다 .
19.9.2 인스턴스에 의한 프로토타입의 교체
프로토타입은 생성자 함수의 prototype 프로퍼티뿐만 아니라 인스턴스의 proto 접근자 프로퍼티를 통해 접근할수 있다. 따라서 인스턴스의 proto 접근자 프로퍼티 는 Object.setPrototypeOf 를 통해 프로토 타입을 교체할수 있다 .
function Person(name) {
this.name = name;
}
const me = new Person("suha");
//프로토 타입으로 교체할 객체
const parent = {
sayHello() {
console.log(`hi! my name is ${this.name}`);
},
};
//me 객체의 프로토 타입을 parent 객체로 교체
Object.setPrototypeOf(me, parent);
//me.__proto__ = parent
me.sayHello();
//프로토타입을 교체하면 constructor 프로퍼티와 생성자 함수간의 연결이 파괴된다
console.log(me.constructor === Person);
// 프로토 타입 체인을 따라 Object.prototype 의 constructor 프로퍼티가 검색
console.log(me.constructor === Object);
프로토 타입 교체를 통해 객체 간의 상속 관계를 동적으로 변경하는 것은 꽤나 번거롭다.
function Person(name) {
this.name = name;
}
const me = new Person("suha");
//프로토 타입으로 교체할 객체
const parent = {
//constructor 프로퍼티와 생성자 함수 간의 연결을 설정
constructor: Person,
sayHello() {
console.log(`hi my name is ${this.name}`);
},
};
//생성자 함수의 prototype 프로퍼티와 프로토 타입 간의 연결을 설정
Person.prototype = parent;
//me 객체의 프로토타입을 parent 객체로 교체
Object.setPrototypeOf(me, parent);
//me.__proto__ =parent
me.sayHello();
console.log(me.constructor === Person); //true
console.log(me.constructor === Object); //false
console.log(Person.prototype === Object.getPrototypeOf(me));
19.10 instanceof 연산자
객체 instanceof 생성자 함수
우변의 생성자 함수의 prototype에 바인딩된 객체가 좌변의 객체의 프로토타입 체인 상에 존재하면 true로 평가 그렇지 않은 경우에는 false 로 평가
function Person(name) {
this.name = name;
}
const me = new Person("suha");
//true
console.log(me instanceof Person);
//true
console.log(me instanceof Object);
instanceof 연산자는 constructor 프로퍼티가 가리키는 생성자 함수를 찾는것이 아니라
생성자 함수의 prototype에 바인딩된 객체가 프로토타입 체인 상에 존재하는지 확인한
function Person(name) {
this.name = name;
}
const me = new Person("suha");
const parent = {};
Object.setPrototypeOf(me, parent);
console.log(Person.prototype === parent);
console.log(Person.constructor === Person);
Person.prototype = parent;
console.log(me instanceof Person);
console.log(me instanceof Object);
19.11 직접 상속
19.11.1 Object.create 에 의한 직접 상속
명시적으로 프로토타입을 지정하여 새로운 객체를 생성한다.
Object.create 메서드도 다른 객체 방식과 마찬가지로 추상 연산 OrdinaryObjectCreate 호출
Object.create 메서드
- new 연산자 없이도 객체를 생성
- 프로토 타입을 지정하면서 객체를 생성
- 객체 리터럴에 의해 생성된 객체도 상속 받을수 있다.
// null 인 객체 생성 , 생성된 객체는 Object 이므로 체인의 종점에 위치
//obj ->null
let obj = Object.create(null);
console.log(Object.getPrototypeOf(obj) === null); //true
// console.log(obj.toString()); //obj.toString is not a function
//obj => Object.prototype -> null
//obj = {}
obj = Object.create(Object.prototype);
console.log(Object.getPrototypeOf(obj) === Object.prototype); //true
//obj ->Object.prototype -> null
obj = Object.create(Object.prototype, {
x: { value: 1, writable: true, enumerable: true, configurable: true },
});
//위의 코드
//obj = Object.create(Object.prototype)
// obj.x = 1
console.log(obj.x);
console.log(Object.getPrototypeOf(obj) === Object.prototype);
const myProto = { x: 10 };
obj = Object.create(myProto);
console.log(obj.x);
console.log(Object.getPrototypeOf(obj) === myProto);
function Person(name) {
this.name = name;
}
obj = Object.create(Person.prototype);
obj.name = "haha";
console.log(obj.name);
console.log(Object.getPrototypeOf(obj) === Person.prototype);
프로토타입 체인의 종점에 위치하는 객체는 Object.prototype 의 빌트인 메서드를 사용할수 없다
이런 에러를 발생시킬 위험을 없애기 위해 다음과 같이 호출
const obj = Object.create(null)
obj.a = 1;
console.log(Object.prototype.hasOwnProperty.call(obj,'a')
19.11.2 객체 리터럴 내부에서 proto 에 의한 직접 상속
const myProto = { x: 10 };
const obj = {
y: 20,
//객체를 직접 상속 받는다
//obj -> myProto -> Object.prototype => null
__proto__: myProto,
};
console.log(obj.x, obj.y);
console.log(Object.getPrototypeOf(obj) === myProto);
19.12 정적 프로퍼티 /메소드
생성자 함수로 인스턴스를 생성하지 않아도 참조/호출할수 있는 프로퍼티 /메서드
function Person(name) {
this.name = name;
}
Person.prototype.sayHello = function () {
console.log(`hi my name is ${this.name}`);
};
Person.startProp = "static prop";
Person.staticMethod = function () {
console.log("staticMethod ");
};
const me = new Person("suha");
Person.staticMethod(); //static method
// me.staticMethod(); //me.staticMethod is not a function
Person 생성자 함수 객체가 소유한 프로퍼티 /메서드를 정적 프로퍼티 /메서드라고 한다.
Object.create 는 Object 생성자 함수의 정적 메서드
Object.prototype.hasOwnProperty 는 Object.prototype 의 정적 메서드이다 .
따라서 Object 생성자 함수가 생성한 객체로 Object.create는 호출 할수 없다 .
하지만 Object.prototype.hasOwnProperty 은 모든 객체의 프로토타인 체인의 종점
즉 Object.prototype 의 메서드이므로 모든 객체가 호출 가능
function Foo() {
Foo.prototype.x = function () {
console.log("x");
};
}
const foo = new Foo();
foo.x();
Foo.x = function () {
console.log("y");
};
Foo.x();
19.13 프로퍼티 존재 확인
19.13.1 in 연산자
in 연산자는 객체 내에 특정 프로퍼티카 존재하는지 여부를 확인한다.
key = 프로퍼티 키를 나타내는 문자열
Object = 객체로 평가되는 표현식 key in Object
const person = {
name: "suha",
address: "seoul",
};
console.log("name" in person); //true
console.log("address" in person); //true
console.log("age" in person); //false
person에는 없지만 in 연산자가 person 객체가 속한 체인 상에 존재하는 모든 프로토타입에서
toString 검색하기 때문에 toString 은 Object.prototype 이다
console.log('toString' in person) //true
Reflect.has 메서드 또한 in 연산자와 동일하게 작동한다.
const person = { name: "s" };
console.log(Reflect.has(person, "name")); //true
console.log(Reflect.has(person, "toString")); //true
19.14 프로퍼티 열거
19.14.1 for … in 문
for (변수 선언문 in 객체) {..}
const person = {
name: "s",
address: "seoul",
};
//person[key] =value
for (const key in person) {
console.log(key + ":" + person[key]);
}
toString 과 같은 Object.prototype 의 프로퍼티는 왜 열거 되지 않을까?
왜나면 열거 가능 여부를 나타내는 Enumerable 이 false 이기 때문이다 .
for … in 문은 객체의 프로토타입 체인 상에 존재하는 모든 프로토타입의 프로퍼티 중에서
프로퍼티 어트리뷰트 enumerable 값이 true 인 프로퍼티를 순회하며 열거 한다.
프로퍼티 키가 심벌인 경우는 열거하지 않는다 .
const person = {
name: "lee",
address: "seoul",
__proto__: { age: 20 },
};
for (const key in person) {
if (!person.hasOwnProperty(key)) continue;
console.log(key + ":" + person[key]);
}
배열에는 for in 문 대신 for 문이나 for of 를 권장
const arr = [1, 2, 3];
arr.x = 10;
for (const i in arr) {
console.log(arr[i]);
}
for (let i; i < arr.length; i++) {
console.log(arr[i]);
}
arr.forEach((v) => console.log(v));
for (const value of arr) {
console.log(value);
}
Object.values 와 Object.kets 는 객체 자신의 열거 가능한 프로퍼티를 반환
Object.entries 는 키와 값 모두 반환
const person = {
name: "a",
address: "seiu",
__proto__: { age: 20 },
};
console.log(Object.keys(person)); //[ 'name', 'address' ]
console.log(Object.values(person)); //[ 'a', 'seiu' ]
console.log(Object.entries(person)); //[ [ 'name', 'a' ], [ 'address', 'seiu' ] ]
'개발 도서 > 자바스크립트 deepdive' 카테고리의 다른 글
17 생성자 함수에 의한 객체 생성 (0) | 2023.07.11 |
---|---|
18 함수와 일급 객체 (0) | 2023.07.11 |
20 strict mode (0) | 2023.07.11 |
11 원시 값과 객체의 비교 (0) | 2023.07.11 |
12 함수 (0) | 2023.07.11 |