Assignment
미국을 비롯해 전세계 대부분의 나라들이 생일을 기준으로 나이를 계산 합니다. 쉽게 말해 미국은 태어나자마자 0살이고 생일을 지나야 비로소 한 살이 됩니다. 반면에 한국은 태어나자마자 1살이고 연도가 바뀔 때마다 한 살씩 먹습니다. 예를 들어 미국에서는 1995년 9월 12일에 태어났으면 1995년 9월 12일에는 0살이고 1996년 9월 12일이 되야 1살이 됩니다. 그에 비해 한국에서는 1995년 9월 12일에 태어나자마자 1살이고 1996년 1월 1일에 2살이 됩니다. 1살 차이도 크게 생각하는 우리나라 고유의 문화에 비롯한 계산법이 아닌가 추측해 봅니다. 미국이나 다른 나라가 사용하는 나이 계산법은 우리나라에서는 만 나이 라고 하죠.
앞서 말한 만으로 계산한 나이를 구하는 함수인 getWesternAge 함수를 구현해 봅시다.
이 함수는 birthday 라는 인자를 받습니다.
이 birthday 는 Date 객체 입니다. birthday 라는 인자를 넣었을 때, 현재를 기준으로 만으로 계산한 나이를 리턴 해주세요.
birthday 는 string이 아닌 Date 객체라는 걸 명심하세요
--> ???
예를 들어, 오늘이 2020년 7월 21일이고, birthday 값이 다음과 같다면:
1990-03-21T00:45:06.562Z
리턴 값은 30 이 되어야 합니다.
코드 보기전에 Date 객체가 무슨소리지?
일단 Date객체 = Date()
아래의 코드를 한 줄씩 콘솔에 입력 해보면 알 수 있다.
console.log(typeof(new Date())) -> object
const a = new Date()
console.log(a)
console.log(typeof(a)) ->object
Date()함수는 객체이다.
코드
function getWesternAge(birthday) {
//풀이 1.
const birth = new Date(birthday);
const now = new Date();
//풀이 2.
const year = now.getFullYear()- birth.getFullYear();
//풀이 3.
const birthMonth = birth.getMonth()+1;
console.log(birthMonth);
const nowMonth = now.getMonth()+1;
console.log(nowMonth);
const month = nowMonth - birthMonth;
//풀이 4.
if (month < 0 || (month === 0 && now.getDate() < birth.getDate())) {
return year -1;
}
return year;
}
console.log(getWesternAge("1990-03-21"));
풀이
'getDate()' 도 new Date()의 prototype method이 다. 날짜를 불러온다.
복습하면서 다시 알고 넘어갈 것
--> prototype method
복습하면서 제일 많이 접하게 된 문장이다. 이를 정리 해 보겠다.
method -> 객체 안에 있는 함수
// 키:밸류로 저장되어 있는 메서드
const bigtop = {
sayHi: function() {
console.log('Hi!?');
}
};
//화살표 함수로 표현한 메서드
const bigtop = {
sayHi: () => {
console.log('Hi!?');
}
};
// ★★key를 생략하고 function 키워드를 제외한 함수 선언문으로도 메서드를 만들 수도 있다.
const bigtop = {
sayHi() {
console.log('Hi!?');
}
};
prototype ->
자바스크립트의 모든 객체는 프로토타입(prototype)이라는 객체를 가지고 있다.. new Date로 객체를 생성해서 변수에 담으면, 프로토타입(prototype)의 method에 접근 할 수 있다.
const obj = new Object(); // 이 객체의 프로토타입은 Object.prototype입니다.
console.dir(obj);
const arr = new Array(); // 이 객체의 프로토타입은 Array.prototype입니다.
console.dir(arr)
더 쉽게 풀어보기
function grandfather() {}
grandfather.prototype.name = '홍길동' // prototype 안의 name(key) = '홍길동'value 로 저장
console.dir(grandfather) // 직접 확인해보기
function father(){}
father.prototype = new grandfather(); //grandfather 함수를 상속받음
function me(){}
me.prototype = new father();
const what = new me();
console.log(what.name) // 홍길동
console.dir(what) // 이 결과는 아래의 캡처본
what = me() 함수를 new 생성자를 이용해서 상속받았고(객체 그대로 넘겨 받음),
me() = father()함수를 new 생성자를 이용해서 상속받았고,
father도 grandfather()함수를 new생성자로 상속받았다,
위에 dir 사진을 보면 me 바로아래에 '[[prototype]]'으로 'grandfather'가 있고 또 그 아래에 똑같이 한번 더 있는 이유가 뭘까?? --> 아직 해결 못함..
2개의 grandfather 어디를 나타내는가 확인을 할 수 있게 아래처럼 코드를 수정 해 보았다.
function grandfather() {}
grandfather.prototype.name = '홍길동'
function father(){}
father.prototype = new grandfather();
father.prototype.here = 'here father'
function me(){}
me.prototype = new father();
me.prototype.here = 'here me'
const what = new me();
console.dir(what)
결과
어,?? [[Prototype]]: grandfather 안에 here: "here me" 가있네??
바로 변수에 담아 보았다.
const wat = new grandfather();
console.log(wat.here);
하지만 undefined,, father를 거치고, me를 거쳐서 here :"here me" 가 생긴 것이기에
바로 grandfather를 생성자로 변수로 할당하면, 당연히 prototype에 담겨 있지 않는 것이다.
자바스크립트는 특정 객체의 프로퍼티나 메소드에 접근하려고 할 때 해당 객체에 접근하려는 프로퍼티 또는 메소드가 없다면 [[Prototype]]이 가리키는 링크를 따라 자신의 부모 역할을 하는 프로토타입 객체의 프로퍼티나 메소드를 차례대로 검색한다. 이것을 프로토타입 체인이라 한다.