러닝 자바스크립트 9장 정리
객체
for ... in
- 객체의 프로퍼티를 순회하는데 사용
- for (변수 in 객체) {
구문
}
- 본문은 객체의 각 프로퍼티에 대해 한 번씩 실행
- 반복에 앞서 객체 프로퍼티 중 하나의 이름이 변수에 문자열 타입으로 할당 됨
const SYM = Symbol();
const o = { a: 1, b: 2, c: 3, [SYM]: 4 };
for (let prop in o) {
if (!o.hasOwnPreperty(prop)) continue;
console.log('${prop}: ${o[prop]}');
}
Object.keys
- 객체에서 나열 가능한 문자열 프로퍼티를 배열로 반환
- 객체의 프로퍼티 키를 배열로 가져와야 할 때 편리
const o = { a:1, x:2, b:3, g:4, xy:5 };
Object.keys(o)
.filter (prop => prop.match(/^x/))
.forEach (prop => console.log (${prop}: ${o[prop]}'));
객체지향 프로그래밍
- 클래스 : 추상적이고 범용적인 것 (ex 어떤 자동차)
- 인스턴스 : 구제척이고 한정적인 것 (ex 특정 자동차)
- 메서드 : 인스턴스의 기능 (ex 자동차의 기능)
- 클래스 메서드 : 클래스에 속하지만 특정 인스턴스에 묶이지는 않는 기능 (ex 시동을 거는 기능)
클래스 생성
class Car {
constructor(){
}
}
- 새 클래스 Car 생성
인스턴스 생성
const car1 = new Car();
const car2 = new Car();
- 새 인스턴스 생성 (만들떄는 new 키워드 사용)
클래스 예제
class Car {
constructor(make, model) {
this.make = make;
this.model = model;
this.userGears = ['P', 'N', 'R', 'D'];
this.userGear = this.userGears[0];
}
shift (gear) {
if (this.userGears.indexOf(gear) < 0)
throw new Error('Invalid gear : ${gear}');
this.userGear = gear;
}
}
const car1 = new Car ("Tesla", "Model s");
const car2 = new Car ("Mazda", "3i");
car1.shift('D');
car2.shift('R');
- car1.shift('D')를 호출하면 this는 car1에 묶임 car2.shift('R')또한 마찬가지이다.
car1.userGear // "D"
car2.userGear // "R"
프로토타입
- class는 ES6에 들어오면서 생성, 전까지는 클래스를 만든다는 것은 클래스 생성자로 사용할 함수를 만든다는 의미였음
- 클래스와 인스턴스에서 사용가능한 메서드 (항상 대문자로 표기)
- ES6에서 변화 Car.prototype.shift ==> Car#shift
- new 키워드로 새 인스턴스를 만들었을 때 new 키워드로 만든 새 객체는 생성자의 prototype 프로퍼티에 접근가능
- 객체 인스턴스는 prototype 프로퍼티를 __proto__ 프로퍼티에 저장
- __proto__는 prototype이 구현되었는지 확인용으로 사용
상속
- 클래스의 인스턴스는 클래스의 기능을 모두 상속
class Vehicle {
constructor() {
this.passengers = [];
console.log("Vehicle created");
}
addPassenger(p) {
this.passenger.push(p);
}
}
class Car extends Vehicle {
constructor() {
super();
console.log("Car created");
}
deployAirbags() {
console.log("BWOOSH"0;
}
}
- extends => Car를 Vehicle의 서브클래스로 만듬
- super() => 슈퍼클래스의 생성자를 호출하는 함수 (서브클래스에서는 이 함수를 반드시 호출해야함)
다형성
- 객체지향 언어에서 여러 슈퍼클래스의 멤버인 인스턴스를 가리키는 것
- instanceof => 객체가 클래스의 인스턴스인지 확인해주는 연산자
다중상속 (다시 보기 이해X)
- 클래스가 슈퍼클래스 두개를 가지는 기능
- 다중상속의 문제를 해결하기 위한 개념 => 믹스인
- 믹스인 : 기능을 필요한 만큼 섞어 놓은 개념 (어떤 기능, 어떤 객체라도 추가 가능)
class InsurancePolicy {}
function makeInsurable(o) {
o.addInsurancePolicy = function(p) {this.insurancePolicy = p; }
o.getInsurancePolicy = function() { return this.insurancePolicy; }
o.isInsured = function() { return !!this.insurancePolicy; }
}
makeInsurable(Car.prototype);
const car1 = new Car();
car1.addInsurancePolicy(new InsurancePolicy());