Object Orieted Programming (OOP)
객체지향 프로그래밍
객체를 이용해서 코드를 정리
물건을 발명하는것과 유사
까마귀 => 전화기
객체는 우리가 만들고자 하는것에 정보, 기능, 행동을 가짐
관련 데이터, 기능을 하나의 객체로 묶어서 만든다
oop 장점
가독성이 좋다
oop 단점
객체안의 정보 사용자가 조작 가능
=>해결하기 위한 방법이 캡슐화
캡슐화 Encapsulation
외부에서 함부로 접근할 수 없도록 내부정보 보호
// 정보 노출 유무는 상황에 맞게
1
2
3
4
5
6
7
8
9
10
11
12
|
var num = {
a : 0,
add: function () {
this.a = 100;
},
minus: function () {
this.a = 50;
}
};
num.a = 99;
console.log(num.a); //99
// 사용자가 num객체의 a속성을 조작 가능하다.
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
var num = (function() {
var a = 0;
return {
find : function () {
console.log("a를 찾자", a);
},
add : function () {
a++;
},
minus : function () {
a--;
}
};
})();
console.log(num);
console.log(num.a);
// num 변수는 함수 스코프 안에 a 변수가 선언되어서 외부에서 접근 X
|
추상화 Abstraction
복잡한 구동 방식을 사용자로부터 숨긴다.
// 사용자는 구동 방식을 알 필요 없이, 명령어 하나로
원하는 행동 가능
객체를 만들시 교려해야할것
ex) 똑같은 함수를 100개 만들어야 한다.
문제 :
변수에 똑같은 함수 일일이 만들어야함
만약 함수의 내용이 바뀔시 모두 수정 해줘야 함
=> 이럴때 사용하는것 팩토리함수
팩토리함수 Factory Function
생산을 해주는 함수
객체를 만들어서 제공해주는 함수
//생성자 함수가 아니어야한다.
1. 객체를 리턴해주는 함수
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
function fac () {
return {
a : function() {
console.log("거북");
},
b : function() {
console.log("파이리");
}
}
}
var fac1 = fac();
console.log(fac1);
//fac와 똑같은 함수를 만든다.
|
2. factory function
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
var fac = {
a : function() {
console.log("거북");
},
b : function() {
console.log("파이리");
}
}
function createPokemon () {
return Object.create(fac);
}
var fac1 = createPokemon();
console.log(fac1);
var d = {
D: "디그다드"
}
var fac2 = Object.create(d);
console.log(fac2);
// createPokemon 실행 결과 새 객체를 만들고
// 괄호안의 객체를 리턴해줌
|
3. constructor function
단점 :
prototype Chain 염두에 두어야 함
this가 중요해짐
1
2
3
4
5
6
7
8
9
10
11
12
13
|
function Con () {
this.n = 0;
}
Con.prototype.add = function() {
this.n = 100;
}
Con.prototype.minus = function() {
this.n = 50;
}
var con = new Con();
console.log(con); // 100
|
Inheritance 상속
생성자를 재할당 해준다.
//순서가 중요함
부모, 자식 우리가 아는 상속의 개념이 아니다.
=> 쓸 수 있는 권한을 가지게 됨
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
function Food (foodName) {
this.favoriteFood = foodName;
}
Food.prototype.changefavoriteFood = function (foodName) {
this.favoriteFood = foodName;
}
function Bread (foodName) {
}
var bread = new Bread("creamBread");
bread.prototype = Object.create(Food.prototype);
// bread의 prototype으로 새 객체를 만든 후
// Food의 prototype object를 넣는다.
// 새 객체를 만들어서 Food의 prototype을 넣어주는것이기 때문에
// 주소값이 다르다
// Food.prototype === bread.prototype // false
bread.prototype.constructor = bread;
// Food의 prototype과 똑같으니 constuructor가 Food로 되어있기 때문에,
// bread의 constuructor를 bread로 바꿔줌
console.log(bread);
er
|
'JavaScript' 카테고리의 다른 글
promise (0) | 2020.01.20 |
---|---|
Asynchronous, Higher Order Function, Event Loop (0) | 2020.01.12 |
ES2015 , ES6 (0) | 2019.11.18 |
var, let, const 차이 (0) | 2019.11.13 |
event delegation, 버블링, 캡쳐링 (0) | 2019.10.12 |