
let user = {
name: "John",
age : 45
}
console.log(user.name);
// John
console.log(user.hasOwnProperty("email"));
// false
- hasOwnProperty는 어디서 왔나요?
현재 user 객체 변수에는 두 개의 속성(name, age)만 있는데
hasOwnProperty는 어디서 나온 것일까?(객체 내부에는 메소드가 없다.)
user 객체 변수를 콘솔로 찍어보면, [[Prototype]] : Object라는 것을 확인할 수 있다.
아래를 내리다보면, hasOwnProperty라는 메소드를 찾을 수 있다.
그리고 우리는 이것을 가져다 사용할 수 있다.
=> 모든 객체는 global Object prototype을 가지며, 이것을 가져다 사용할 수 있다.
- 그러면 이 Prototype은 무엇인가요?
프로토타입은 자바스크립트 객체가
다른 객체로부터 메서드와 속성을 상속 받는 메커니즘을 말한다.
=> 이것을 프로토타입 체인(prototype chain)이라고 말한다.
위에서 보듯이 prototype object 안에 있는 hasOwnProperty를 상속받아서 사용하고 있다.
이렇게 하므로써 더 적은 메모리를 사용할 수 있고 코드를 재사용할 수 있다.
- 예를 통해 prototype 알아보기
// 생성자(constructor) 함수 => 다른 객체를 만드는 함수.
function Person(name, email, birthday) {
this.name = name;
this.email = email;
this.birthday = new Date(birthday);
this.calculateAge = function() {
const diff = Date.now() - this.birthday.getTime();
const ageDate = new Date(diff);
return Math.abs(ageDate.fetUTCFullYear() - 1970);
}
}
// return을 안 해도 자동으로 객체의 인스턴스를 return 한다.
const john = new Person("john", "john@abc.com", "7-10-91");
const han = new Preson("han", "han@abc.com", "2-8-91");
// 생성자 함수를 사용해서 객체를 만들 때 new 키워드를 사용.
console.log(john);
// Person {name: 'john', email: 'john@abc.com', birthday: Wed Jul 10 1991 00:00:00 GMT+0900 (한국 표준시), calculateAge: ƒ}
john과 han 객체를 찍어봤을 때,
birthday, email, name 값은 서로 다르지만 calculateAge 메소드의 값은 같다.
그렇기 때문에 이 calculateAge 메소드를 prototype으로 옮겨줄 것이다.
1. 첫 번째 방법.
// 생성자(constructor) 함수 => 다른 객체를 만드는 함수.
function Person(name, email, birthday) {
this.name = name;
this.email = email;
this.birthday = new Date(birthday);
}
// return을 안 해도 자동으로 객체의 인스턴스를 return 한다.
// calculateAge 메소드만 따로 빼서 프로토타입으로 만들기.
Person.prototype.calculateAge = function () {
const diff = Date.now() - this.birthday.getTime();
const ageDate = new Date(diff);
return Math.abs(ageDate.fetUTCFullYear() - 1970);
};
const john = new Person("john", "john@abc.com", "7-10-91");
const han = new Person("han", "han@abc.com", "2-8-91");
// 생성자 함수를 사용해서 객체를 만들 때 new 키워드를 사용.
console.log(john);
// Person {name: 'john', email: 'john@abc.com', birthday: Wed Jul 10 1991 00:00:00 GMT+0900 (한국 표준시)}
console.log(han);
// Person {name: 'han', email: 'han@abc.com', birthday: Fri Feb 08 1991 00:00:00 GMT+0900 (한국 표준시)}
2. 두 번째 방법.
Object.create() :
Object.create() 메소드는 지정된 프로토타입 객체 및 속성을 갖는 새 객체를 만든다.
function Person(name, email, birthday) {
let person = Object.create(personPrototype);
person.name = name;
person.email = email;
person.birthday = new Date(birthday);
return person;
}
const personPrototype = {
calculateAge() {
const diff = Date.now() - this.birthday.getTime();
const ageDate = new Date(diff);
return Math.abs(ageDate.fetUTCFullYear() - 1970);
},
};
const john = new Person("john", "john@abc.com", "7-10-91");
const han = new Person("han", "han@abc.com", "2-8-91");
// 생성자 함수를 사용해서 객체를 만들 때 new 키워드를 사용.
console.log(john);
// Person {name: 'john', email: 'john@abc.com', birthday: Wed Jul 10 1991 00:00:00 GMT+0900 (한국 표준시)}
console.log(han);
// Person {name: 'han', email: 'han@abc.com', birthday: Fri Feb 08 1991 00:00:00 GMT+0900 (한국 표준시)}
'Javascript' 카테고리의 다른 글
Sub Class(Inheritance) (0) | 2024.09.04 |
---|---|
ES6 Classes (0) | 2024.09.04 |
OOP(Object-oriented-programming) (0) | 2024.09.03 |
Event 종류 (0) | 2024.09.03 |
DOM Event (0) | 2024.09.03 |
github : https://github.com/dnjfht
포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!