Prototype 본문

2021 프론트 엔드 로드맵 따라가기/JS

Prototype

알 수 없는 사용자 2021. 6. 5. 11:36

ES5에서 상속을 구현하기 위해 만들었다. (ES6에서는 class 키워드를 이용해 똑같이 구현이 가능하다)

pseudo property이기 때문에 loop문을 이용해 해당 속성을 이용한다거나 하는 것이 불가능하다.

 

literal로 object를 생성할 때 항상 object라는 prototype으로부터 상속을 받는다. (object가 최상위 prototype이기 때문)

 

// Object.prototype

// Person.prototype
function Person(firstName, lastName, dob) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.birthday = new Date(dob);
}

// Calculate age
Person.prototype.calculateAge = function () {
  const diff = Date.now() - this.birthday.getTime();
  const ageDate = new Date(diff);
  
  return Math.abs(ageDate.getUTCFullYear() - 1970);
}

// Get fullname
Person.prototype.getFullName = function () {
  return `${this.firstName} ${this.lastName}`;
}

// Gets Married
Person.prototype.getsMarried = function (newLastName) {
  this.lastName = newLastName
}

const jian = new Person("jian", "dev", "11-23-1993");
const mary = new Person("mary", "Johnson", "March 20 1978");

console.log(mary);

console.log(jian.calculateAge());

console.log(mary.getFullName());

mary.getsMarried("Smith");

console.log(mary.getFullName());

console.log(mary.hasOwnProperty("firstName"));  // Object prototype

console.log(mary.hasOwnProperty("getFullName"));  // Object prototype

'2021 프론트 엔드 로드맵 따라가기 > JS' 카테고리의 다른 글

ES6 class  (0) 2021.06.05
[중요] Prototypal inheritance  (0) 2021.06.05
Built in Constructor  (0) 2021.06.05
Hoisting  (0) 2021.06.05
특정 범위의 랜덤 정수 값 생성 코드  (0) 2021.06.04
Comments