let user = {
name : 'John',
age : 45,
//email : 'john@example.com'
}
console.log(user.name);
console.log(user.hasOwnProperty('email'));
hasOwnProperty는 어디서 왔을까?
현재 user 객체 변수에는 두 개의 속성(name, age)만 있는데 hasOwnProperty는 어디서 왔을까?
-> 모든 객체는 golbal Object prototype을 가진다
prototype은 무엇인가?
프로토타입은 자바스크립트 객체가 다른 객체로부터 메서드와 속성을 상속받는 메커니즘을 말합니다. 이것을 프로토타입 체인(prototype chain)이라고도 말합니다. 위에서 보듯이 prototype object 안에 있는 hasOwnProperty를 상속받아서 사용하고 있습니다. 이렇게 하므로 인해서 더 적은 메모리를 사용할 수가 있고 코드를 재사용할 수 있습니다.
생성자 함수
1. 생성자(constructor) 함수는 다른 객체를 만드는 함수이다.
2. 생성자 함수는 이름의 첫 글자가 대문자이다.
2. return을 안 해도 자동으로 객체의 인스턴스를 return 한다.
3. 생성자 함수를 사용해서 객체를 만들 때 new 키워드를 사용한다.
방법 1
함수를 prototype에 넣어서 재사용하기
변경 전 코드
function Person(name, email, birthday){
this.name = name;
this.email = email;
this.birthday = new Date(birthday);
this.calculateAge = function(){
const diff = Date.new() - this.getTime();
const ageDate = new Date(diff);
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
}
변경 후 코드
function Person(name, email, birthday){
this.name = name;
this.email = email;
this.birthday = new Date(birthday);
}
Person.prototype.calculateAge = function() {
const diff = Date.new() - this.getTime();
const ageDate = new Date(diff);
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
방법 2
또한 Object.create()을 이용해서도 객체의 prototype을 지정해 줄 수 있습니다.
function Person(name, email, birthday){
const person = Object.create(personsPrototype);
person.name = name;
person.email = email;
person.birthday = new Date(birthday);
return person;
}
const personsPrototype = {
calculateAge: function() {
const diff = Date.new() - this.getTime();
const ageDate = new Date(diff);
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
}
const john = new Person('john', 'john@example.com', '7-10-91');
const hann = new Person('han', 'john@example.com', '2-11-91');
console.log(john);
console.log(hann);