코어자바스크립트 7장 part1 (클래스)

KHW·2021년 3월 8일
0

코어자바스크립트

목록 보기
16/19

클래스

ex)
음식 => 고기 ,채소, 과일 (추상적인 개념)
과일 => 배, 사과,바나나(구체적이고 실존하는 사물)

superClass : 음식
subClass : 과일

하위 개념은 상위개념을 포함하면서 더 구체적인 개념이 추가됩니다.


인스턴스

어떤 클래스의 속성을 지니는 실존하는 개체


스태틱 메소드 vs 프로토타입 메서드

스태틱메서드 : 인스턴스에서 직접 접근할 수 없는 메서드
프로토타입메서드 : 인스턴스에서 직접 호출 할 수 있는 메서드

let a = [1,2]
a.isArray() //type error 
a.push(10)

생성자함수 Array의 스태틱 메소드인 isArray는 인스턴스인 a에서 직접 접근할 수 없으나 프로토타입 메소드인 push는 직접 접근이 가능하다.


Rectangle, Square클래스

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());		//12

var Square = function(width){
  this.width = width;
};

Square.prototype.getArea = function(){
  return this.width * this.width;
}
var sq = new Square(5);
console.log(sq.getArea())		//25

Square 클래스 변형

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.call(this,width,width);
};

Square.prototype = new Rectangle();
var sq = new Square(5)
console.dir(sq)

Square를 Rectangle의 하위 클래스로 삼을 수 있다.


문제점

결과를 보면 해당 Square.prototype에 값이 존재하는 문제점이 발생한다.


해결방법

  1. 빈 함수를 다리 역할을 부여
  2. Object.create 활용

1.


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.call(this,width,width);
};

Square.prototype = new Rectangle();
var sq = new Square(5)

console.dir(sq)

var Bridge = function(){};
Bridge.prototype = Rectangle.prototype;
Square.prototype = new Bridge();
Object.freeze(Square.prototype);

var sq1 = new Square(10)

console.dir(sq1)

위와 다르게 __proto__에 값이 존재하지않는다.


2.

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.call(this,width,width);
};

Square.prototype = new Rectangle();
var sq = new Square(5)

console.dir(sq)

Square.prototype = Object.create(Rectangle.prototype);
Object.freeze(Square.prototype);

var sq1 = new Square(7);

console.dir(sq1);

마찬가지의 결과가 나온다.


출처

코어자바스크립트

profile
나의 하루를 가능한 기억하고 즐기고 후회하지말자

0개의 댓글