let ageCounter1 = {
age: 20,
increase: function() {
this.age++;
},
decrease: function() {
this.age--;
},
getAge: function(){
return this.age;
}
}
ageCounter1.increase();
ageCounter1.getAge(); // 21
ageCounter1 하나밖에 못씀, 재사용성 떨어짐
function makeAgeCounter() {
let age = 20;
return {
increase: function() {
age++;
},
decrease: function() {
age--;
},
getAge: function() {
return age;
}
}
}
let ageCounter1 = makeAgeCounter();
ageCounter1.decrease();
ageCounter1.getAge(); // 19
let ageCounter2 = makeAgeCounter();
ageCounter2.increase();
ageCounter2.increase();
ageCounter2.getAge() // 22
함수 표현으로 리턴에 객체표현, 재사용가능
function Car(brand,name,color){
// 인스턴스가 만들어질때 실행되는 코드
}
class Car {
constructor(brand,name,color){
//인스턴스가 만들어질때 실행되는 코드, 최근에 자주씀
}
}
let avante = new Car('bmw', 'mini, 'white')
class Car{
constructor(brand, name, color){ //생성자
this.brand = brand(매개변수);
this.name = name;
this.color = color;
}
}
function Car(brand, name, color){
this.brand = brand;
}
Car.prototype.refuel = function() {
console.log(this.brand + '가 운전을 시작합니다');
}
let avante = new Car('hyundai');
avante.drive(); // 현대가 운전을 시작합니다.
class Car{
constructor(brand, name, color){ //생성자
this.brand = brand(매개변수);
}
drive() {
}
}
let avante = new Car('hyundai');
avante.brand; // hyundai
avante.drive();
이전에 C등은 절차지향 프로그래밍이었음. 순차적 명령의 조합, 함수로이동하는게 전부였음
OOP의 모든건 객체로 그룹화됨
화면에 보이는 하나의 요소를 객체단위로 생각하면, 보다 쉬운 코드를 작성할수있게됨
객체지향 잘 이해, 응용하는게 중요함. 4가지 기본적인 개념이 있음
__proto__
속성으로 객체 인스턴스에 구현하고있음 class Human {
constructor(name, age) {
this.name = name;
this.age = age;
}
sleep() {
console.log(`${this.name}은 잠에 들었습니다`);
}
}
let kimcoding = new Human('김코딩', 30);
// 실습해보세요
Human.prototype.constructor === Human;
Human.prototype === kimcoding.__proto__;
Human.prototype.sleep === kimcoding.sleep; //다 true 나옴