메서드 호출: 객체.메서드()
//여러 동작을 하는 객체를 만들었다.
let pumpSyrup = {
pumpping: 0,
increase: function(){ this.pumpping++},
decrease: function(){ this.pumpping--},
getValue: function(){ return this.pumpping}
}
pumpSyrup.increase();
pumpSyrup.getValue();
pumpSyrup.decrease();
pumpSyrup.getValue();
클로저를 이용해 새로운 객체 생성
클로저 모듈 패턴을 이용한다.
변수를 함수 스코프에 가둬 노출시키지 않는다.
//변수로 선언하지 않고 함수로 선언해 객체생성모듈을 만들었다.
//위와 달리 this.value를 찍는 경우 0, nan이 반환된다. 왜일까?
//this를 사용하면 public 멤버가 된다.
//new 키워드로 객체를 생성하지 않으면 this는 생성된 객체에 바인딩되지 않고 전역객체에 연결된다.
function custom(){
let value = 0;
return {
increase: function(){value++},
decrease: function(){value--},
getValue: function(){return value}
}
}
let syrup = custom()
syrup.increase()
syrup.getValue()
let milk = custom()
milk.decrease()
milk.getValue();
let beganMilk = custom()
beganMilk.increase()
beganMilk.getValue()
function Dog(name, tail, color){}
class Dog { //es6 생성자 함수. 인스턴스가 만들어질 때 실행된다.
constructor(name, tail, color){}
}
let seolgi = new Dog('seolgi', 'long', 'white');
//각각의 인스턴스는 클래스의 고유한 속성과 메서드를 갖게 된다.
인스턴스 객체를 의미한다.
파라미터로 넘어온 속성 등은 인스턴스 생성시 지정하는 값이며 this에 할당한다는 것은 만들어진 인스턴스에 해당 속성을 부여하겠다는 의미이다.
ES5 : prototype 키워드를 사용해야 메서드 정의 가능
ES6 : 생성자 함수와 함께 클래스 안쪽에 묶어서 정의
function Dog(name, tail, color){}
Dog.prototype.giveHand = function(){}
class Dog { //es6
constructor(name, tail, color){}
sit(){}
}
class Dog{
constructor(name, tail, color) { //생성자함수
this.name = name; //this객체는 설기
this.tail = tail;
this.color = color;
}
sit(){
console.log(this.name + '가 앉았다!');
}
}
let seolgi = new Dog('seolgi', 'long', 'white'); //인스턴스
seolgi.color; //white
seolgi.sit(); //seolgi가 앉았다!
- this 함수가 실행될 때 해당 스코프마다 생성되는 고유한 실행 context
new 키워드로 인스턴스를 생성했을 때에는 해당 인스턴스가 바로 this의 값이 된다.- constructor 인스턴스가 초기화될 때 실행하는 생성자 함수
- prototype 모델의 청사진을 만들 때 쓰는 원형 객체(original form)
배열은 Array의 인스턴스이다.
따라서 new Array('','','')의 방식으로 배열 생성이 가능하다.
//es5
function Custom(value) {
this.value = 0;
}
Custom.prototype.increase = function (){
value = this.value++;
}
Custom.prototype.decrease = function (){
value = this.value--;
}
Custom.prototype.getValue = function () {
return this.value;
}
let milk = new Custom;
milk.increase();
milk.getValue(); //1
milk.decrease();
milk.getValue(); //0
//es6
class Custom {
constructor(){
this.value = 0;
}
increase(){this.value++}
decrease(){this.value--}
getValue(){return this.value}
}
let milk = new Custom();
milk.decrease();
milk.getValue(); //-1