: 똑같은 기능을 하는 함수를 여러개 만들 수 있다.
즉, 모듈을 여러 개 만들어서 원본 함수를 바꾸지 않아도 방향을 바꿔 사용할 수 있다.
우선 메서드가 있는 변수를 만들어 보겠다.
let calcurate = {
value: 0;
increase: function() {
this.value++
},
decrease: function() {
this.value--
},
getValue : function() {
return this.value
}
}
calcurate.increase()//1
calcurate.increase()//2
calcurate.decrease()//1
calcurate.increase()//2
(위의 객체에서 주의해야 할 점은?
👀바인딩이란?
컴퓨터 프로그래밍에서 각종 값들이 확정되어 더 이상 변경할 수 없는 구속(bind) 상태가 되는 것을 말한다.
위 예제를 클로저를 이용해서 새로운 객체를 생성해보면 아래와 같다.
function makeCalcurator = {
let value: 0;
increase: function() {
value++
},
decrease: function() {
value--
},
getValue : function() {
return value
}
}
let calcu1 = makeCalcurator()
calcu1.increase()
calcu1.increase()
calcu1.increase()
calcu1.getValue()//3
let calcu2 = makeCalcurator()
calcu2.decrease()
calcu2.decrease()
calcu2.decrease()
calcu2.getValue()//3
class와 instance를 한마디로 표현하자면!
class는 청사진.
instance는 청사진을 바탕으로 한 객체라고 할 수 있다.
class 예제를 EM5와 최근에 나온 EM6를 비교해보면 아래와 같다.
📌EM5
function Dog( weight, name, color ) {
this.weight = weight;
this.name = name;
this.color = color;
Dog.prototype.eat = function() {
console.log(this.name + '는 사료를 먹습니다');
}
}
📌EM6
class Dog {
constructor ( weight, name, color ) { //weight, name, color는 속성,constructor는 생성자
this.weight = weight; // this : 함수가 실행될 때, 해당 scope 마다 생성되는 고유한 실행
this.name = name;
this.color = color;}
eat() {
console.log(this.name + '는 사료를 먹습니다');
}
}
let mango = new Dog('4', 'mango', 'ivory')//EM6 예제에는 instance도 추가해보았다.
console.log(mango.name) //'mango'
mango.eat()//"mango는 사료를 먹습니다"
+예제 추가