You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
functionRectangle(w,h){varwidth=w;varheight=h;this.getWidth=function(){returnwidth;};this.getHeight=function(){returnheight;};this.setWidth=function(w){if(w<0){throw'길이는 음수 no';}else{width=w;}};this.setHeight=function(h){if(h<0){throw'높이는 음수 no';}else{height=h;}};}Rectangle.prototype.getArea=function(){returnthis.getWidth()*this.getHeight();};functionSquare(length){// Rectangle 객체의 속성을 Square 객체에 추가this.base=Rectangle;// 꼭 base 라고 명명할 필요는 없음this.base(length,length);}// Rectangle 객체의 프로토타입이 가진 속성 또는 메서드를 Square 객체의 프로토타입에 복사Square.prototype=Rectangle.prototype;Square.prototype.constructor=Square;varrectangle=newRectangle(5,7);varsquare=newSquare(5);console.log(rectangle.getArea()+': '+square.getArea());console.log("square instanceof Rectangle: "+String(squareinstanceofRectangle));
생성자 함수 Square의 프로토타입 constructor() 메서드에 Square를 다시 넣는 부분이 없어도 정상작동함
하지만, 직접 square 객체의 constructor() 메서드를 출력해보면 생성자 함수 Square가 아니라 생성자 함수 Rectangle을 가리킴
따라서 프로토 타입의 생성자 함수를 재정의 한것
// Square.prototype.constructor = Square
Square.prototype.constructorƒRectangle(w,h){console.log("constructor in Rectangle");varwidth=w;varheight=h;this.getWidth=function(){returnwidth;};this.getHeight=…}
Square.prototype.constructor = Square
Square.prototype.constructorƒSquare(length){console.log("constructor in Square");this.base=Rectangle;this.base(length,length);}
ECMAScript 6
클래스 기반의 객체지향 언어 이념을 도입
class 키워드 도입
생성자 함수를 constructor 함수가 처리
메서드 선언을 프로토타입 안에 선언하는 것이 아니라 class 블록 내부에 선언
게터, 세터 작성 방법 변경
get을 붙여 만든 메서드는 값을 가져오는 행위를 할 때 자동으로 호출
set을 붙여 만든 메소드는 값을 넣는 행위를 할 때 자동으로 호출
기존 생성자 함수로 게터, 세터 구현할 때 보다 간단
2017년 4월 기준 게터, 세터를 사용하면 스택 추적(오류 확인)이 어렵고, 유지 보수가 어렵고, 메서드 체이닝에 활용하기 힘들다는 이유로 사용 자제