var MyMath = {
PI:Math.PI,
random:function(){
return Math.random();
},
floor:function(val){
return Math.floor(val);
}
}
var kim = {
name:'kim',
first:10,
second:20,
third:30,
sum:function(){
return this.first+this.second+this.third;
}
}
var lee = {
name:'lee',
first:10,
second:10,
third:10,
sum:function(){
return this.first+this.second+this.third;
}
}
console.log("kim.sum()", kim.sum()); // kim.sum 60
console.log("lee.sum()", lee.sum()); // kim.sum 30
객체를 하나씩 수동으로 만들어내고 항목을 수정하려 하면 같은 취지의 객체를 모두를 수정해야 했다.
var d1 = new Date('2019-4-10');
console.log('d1.getFullYear()', d1.getFullYear()); // 2019
console.log('d1.getMonth()', d1.getMonth()); // 3
우리가 Date를 사용할 때 new를 항상 붙여줬고, Date의 내부 설계를 모르지만 사용할 수 있었다. → new라는 생성자를 통해 객체를 만들어서 리턴하는 것이다.
function Person(name, first, second, third){
this.name=name;
this.first=first;
this.second=second;
this.third=third;
this.sum = function(){
return this.first+this.second+this.third;
}
}
var kim = new Person('kim', 10, 20, 30);
var lee = new Person('lee', 10, 10, 30);
console.log("kim.sum()", kim.sum()); // 60
console.log("lee.sum()", lee.sum()); // 30
그냥 Person을 호출하면 그냥 함수일 뿐이기에 리턴하지 않으면 결괏값이 없지만, new를 붙이면 객체를 생성하는 생성자 함수가 된다.
생성자 함수에 인자로 값을 넣어주면 손쉽게 객체를 생성하고 수정할 수 있다.
하나의 생성자를 이용해서 만든 모든 객체가 공통적으로 사용할 수 있는 함수를 만들 수 있다.
function Person(name, first, second, third){
this.name=name;
this.first=first;
this.second=second;
}
Person.prototype.sum = function(){
return 'prototype : '+(this.first+this.second);
}
var kim = new Person('kim', 10, 20);
kim.sum = function(){
return 'this : '+(this.first+this.second);
}
var lee = new Person('lee', 10, 10);
console.log("kim.sum()", kim.sum()); // prototype : 30
console.log("lee.sum()", lee.sum()); // prototype : 20
prototype을 사용해서 Person이라는 생성자 함수에 공통적으로 사용할 sum이라는 메소드를 만들 수 있다.