주말공부 - 객체 review

1. 객체, 메소드

  • 속성(property) 라는 용어는 키-값 쌍을 의미한다.
  • 메소드 호출은 객체.메소드() 와 같이 객체 내에서 메소드를 호출하는 방법이다.
  • 아래 예제는 Singleton 패턴이라고 부른다.
  • 메소드 호출 방식을 이용할 떄에는 화살표 함수를 쓰지 않는다.
let counter1 = {
  value:0,
  increase: function() {
    this.value ++ // 메소드 호출을 할 경우 this 는 counter1을 가리킨다.
    },
  decrease: function() {
    this.value --
    },
  getValue: function() {
    return this.value
  }
}
counter1.increase()
counter1.decrease()
counter1.decrease()
counter1.getValue() //2
  • 클로저를 이용해 매번 새로운 객체 생성하기 : singleton 패턴은 단 하나의 객체만 만들 수 있다. 똑같은 기능을 하는 카운터를 여러 개 만들려면 객체를 여러개 만들 필요는 없다.
function makeCounter() {
  return {
    value :0,
    increase : function() {
      this.value ++ // 메소드 호출을 할 경우, this 는 makeCounter 함수가 리턴하는 익명의 객체이다.
    },
    decrease : function() {
      this.value --
    },
    getValue : function() {
      return this.value;
    }
  }
}

let counter1 = makeCounter()
counter1.increase()
counter1.getValue() //1

let counter2 = makeCounter()
counter2.decrease()
counter2.decrease()
counter2.getValue() //-2

2. 객체지향 프로그래밍

  • 하나의 모델이 되는 청사진(=class)을 만들고, 그 청사진을 바탕으로 한 객체(=instance)를 만드는 프로그래밍 패턴
  • 인스턴스를 만들때 : new 키워드를 이용해 만든다.
let avante = new Car ('blue') //new 키워드로 인스턴스 생성시 해당 인스턴스가 바로 this의 값이 된다.
  • 클래스를 만들때 : 일반 함수 정의하듯 만들어진다 (첫글자 대문자)
function Car(color) {}
class Car{
  constructor(brand, name, color) { //인스턴스가 초기화 될 때 실행하는 생성자 함수
    this.brand = brand;
    this.name = name;
    this.color = color; // 만들어질 인스턴스에 해당 브랜드, 이름 , 생상을 부여하겠다는 뜻
  }
}
  • 우리가 배열을 정의 하는 것은 Array의 인스턴스를 만들어 내는 것과 동일하다.

3. this 키워드

  • 함수 실행시 호출방법에 의해 결정되는 특별한 객체이다. 맥락에 따라 this 는 다르게 결정된다.
  • 함수를 실행하는 방법
    • function 호출 ex) foo()
    • method 호출 ex) obj.foo() -> this 값 = 부모객체
    • new 키워드를 이용한 생성자 호출 ex)new Foo() -> this 값 = 새롭게 생성된 인스턴스 객체
    • .call 또는 .apply 호출 -> this 값 = 첫번째

4. call, apply, bind 메소드

  • call, apply호출은 명시적으로 this 를 지정하고 싶을떄 사용한다. 첫번째 인자가 항상 this 값이 된다
    let allDivs = document.querySelectorAll('div'); // 유사배열이므로 map 메소드 존재 x
    [].map.call(allDivs, function(el) { //하지만 Array.prototype 으로부터 map 메소드 빌려와 this 를 넘겨 map 실행 가능
    return el.className
    })
    
  • bind는 당장 실행하는 것이 아닌 바인딩 된 함수를 리턴하는 함수이다.
    fn.bind(this , 인자1, 인자2 ...)
    

Updated: