it 책/코어 자바스크립트

7장 클래스

테오구 2022. 5. 20. 14:57
728x90

Array를 생성자 함수 new와 함께 호출하면 인스턴스가 생성됩니다. 이때 Array를 일종의 클래스라고 하면, Array의 prototype 객체 내부 요소들이 인스턴스에 상속된다고 볼 수 있습니다. 엄밀히 말하면 프로토 타입 체이닝에 의한 참조지만

인스턴스에 상속되는지 여부에 따라 스태틱 멤버인스턴스 멤버로 나뉩니다.

다른 클래스 기반 언어와 달리 자바스크립트에서는 인스턴스에서도 직접 메서드를 정의할 수 있기 때문에 ‘인스턴스 메서드’라는 명칭보다는 프로토 타입 메서드라고 부르는 편이 좋습니다.

const Rectangle = function(width, height) {
	this.width = width
	this.height = height
}
Rectangle.prototype.getArea = function(){
	return this.width * this.height
}
Rectangle.isRectangle = function(instance){
	return instance instance Rectangle &&
			instance.width > 0 && instance.height > 0
}

const rect1 = new Rectangle(3,4)
console.log(rect1.getArea())                  // 12 (0)
console.log(rect1.isRectangle(rect1))         // Error (x)
console.log(Rectangle.isRectangle(rect1))     // true

13번째 줄에서 호출한 getArea는 실제로는 react1.proto.getArea에 접근하는데, 이때 __proto__를 생략했으므로 this가 rect1인 채로 실행되니 결과적으로 width * rect1.height의 계산값이 반환될 것

이처럼 인스턴스에서 직접 호출할 수 있는 메서드가 바로 프로토타입 메서드 입니다.

14번째 줄은 rect1에 해당 메서드가 있는지 검색했는데 rect1.__proto__에도 없으며 rect1.proto.proto(Object.prototype)에도 없습니다.

그래서 에러가 발생하는데 이를 스태틱 메서드라고 합니다.

스태틱 메서드는 15번째 줄 처럼 생성자함수를 this로 해야만 호출할 수 있습니다.

클래스 상속

const Grade = function(){
	const args = Array.prototype.slice.call(arguments)
	for (let i = 0; i < args.length; i++){
		this[i] = args[i]
	}
	this.length = args.length
}
Grade.prototype = []
const g = new Grade(100,80)
g.push(90)
console.log(g)  // Grade { 0: 100, 1:80, 2:90, length: 3}

delete g.length
g.push(90)
console.log(g) // Grade { 0: 70, 1:80, 2:90, length: 1}

12번째 줄에서 length 프로퍼티를 삭제하고 다시 push한 값이 0번째 인덱스에 들어갔고, length가 1이 됐습니다.

내장 객체인 배열 인스턴스의 length 프로퍼티는 configurable 속성이 false라서 삭제가 불가능하지만

Grade클래스의 인스턴스는 배열 매서드를 상속하지만 기본적으로는 일반 객체의 성질을 그대로 지니므로 삭제가 가능해서 문제가 됩니다.

728x90

'it 책 > 코어 자바스크립트' 카테고리의 다른 글

6장 프로토 타입  (0) 2022.05.12
5장 클로저  (0) 2022.05.07
3장 this 정리  (0) 2022.05.03
2장 실행 컨텍스트  (0) 2022.05.02
1장 정리  (0) 2022.05.01