코어자바스크립트 chapter 7
👉클래스란?
자바스크립트에서의 클래스는 생성자 함수를 new 연산자와 함께 호출하면 인스턴스가 생성된다.
이때 Array의 prototype 내부요소들이 인스턴스에 상속된다.
(프로토타입 체이닝에 의한 참조)
-클래스는 일급객체다
- 무명의 리터럴로 생성가능 (런타임에 생성가능)
- 변수나 자료구조에 저장가능
- 함수의 매개변수에 전달가능
- 함수의 반환값으로 사용가능
- 클래스에서 정의할 수 있는 메서드 종류
- constructor(생성자)
- 프로토타입 메서드
- 정적 메서드
👉스태틱 메서드란?
var Rectangle = function (width, height) { //생성자함수
this.width = width;
this.height = height;
}
Rectangle.prototype.getArea = function () { //prototype 메서드
return this.width * this.height;
}
Rectangle.isRectangle = function (instance){ //static 메서드
return instance instanceof Rectangle &&
instance.width > 0 && instance.height > 0;
};
var rect1 = new Rectangle(3,4)
console.log(rect1.getArea()); //12 (o)
console.log(rect1.isRectangle(rect1)); //Error(x)
console.log(Rectangle.isRectangle(rect1)); //true
인스턴스에서 static 메서드로 접근할 수 없다.
생성자함수에서 직접 static 메서드를 호출해야 한다.
즉 인스턴스를 생성하지 않아도 호출할 수 있는 메서드다.
클래스 내부에서 메서드를 정의할 때 static키워드를 붙이면 된다.
👉정적 메서드와 프로토타입 메서드의 차이
- 자신이 속해있는 프로토타입 체인이 다르다
- 정적 메서드는 클래스로 호출하고 프로토타입 메서드는 인스턴스로 호출한다.
- 정적 메서드는 인스턴스 프로퍼티를 참조할 수 없지만 프로토타입 메서드는 인스턴스 프로퍼티를 참조할 수 있다.
- 프로토타입 메서드의 this는 프로토타입 메서드를 호출한 인스턴스
- 정적 메서드의 this는 클래스를 가리킴
👉클래스 상속이란?
자바스크립트에서 클래스 상속이란 프로토타입 체이닝을 잘 연결한 것
var Grade = function () {
var args = Array.prototype.slice.call(arguments);
for (var i = 0; i < args.lenth; i++) {
this[i] = args[i];
}
this.length = args.length;
};
Grade.prototype = [];
var g = new Grade(100,80);
//length 프로퍼티 삭제
g.push(90);
console.log(g); //Grade {0: 100, 1:80, 2: 90, length:3}
delete g.length;
g.push(70);
console.log(g); // Grade {0:70, 1:80, 2:90, length:1}
g프로퍼티를 삭제한 뒤 g.push를 했을 때 0번째에 들어가고 length가 1이 되는 까닭
g.__proto__가 빈 배열을 가리키고 있기 때문에
g.length가 없으므로 프로토타입 체이닝을 통해 g.__proto__.length 속성을 가져온 것
빈 배열의 length가 0이므로 값을 할당, length는 만큼 증가
square에서 rectangle을 상속
var Rectangle = function (width, height) {
this.width = width;
this.height = height;
}
Rectangle.prototype.getArea = function () {
return this.width * this.height
}
var rect = new Rectangle(3, 4);
console.log(rect.getArea());
var Square = function (width) {
//Rectangle을 함수로써 호출
Rectangle.call(this, width, width);
}
Square.prototype = new Rectangle();
👉클래스의 인스턴스 생성과정
1. 인스턴스 생성과 this 바인딩
new 연산자와 함께 클래스 호출 하면 클래스가 암묵적으로 빈 객체 생성
해당 객체의 프로토타입으로 클래스의 prototype 프로퍼티가 가리키는 객체 설정
인스턴스는 this에 바인딩
2. 인스턴스 초기화
this에 바인딩되어있는 인스턴스 초기화
인스턴스에 프로퍼티 추가, constructor가 인수로 전달받은 초깃값으로 인스턴스 프로퍼티 값 초기화
3. 인스턴스 반환
완성된 인스턴스가 바인딩 된 this가 암묵적으로 반환