ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Front End] 객체지향 JavaScript 구현
    Web Development/부스트코스 - Front-End(JavaScript) 2020. 4. 22. 15:04

    ✔️ 배열의 함수형 메소드

    웹 프론트엔드에서는 데이터 처리가 점점 증가하고 있다. 배열에 적용되는 다양한 메서드를 통해 데이터 파싱 처리를 손쉽게할 수 있다. 아래와 같은 배열을 다양한 메서드로 조작해보자. 

    var data = [{ title: "hello", content: "간지철철", price: 12000 },
    { title: "crong", content: "괜춘한 상품", price: 5500 },
    { title: "codesquad", content: "쩌는상품", price: 1200 }];

    1️⃣ for, forEach 

    //for를 통한 배열 탐색
    for (var i = 0; i < data.length; i++) {
        console.log(data[i].title, data[i].price)
    }
    
    //forEach를 통한 배열 탐색 : i++이나 length를 판단하는 코드가 없기 때문에 실수를 줄일 수 있고 간편하다.
    data.forEach(function (v) {
        console.log(v.title, v.price);
    });

    2️⃣ map, filter

    map과 filter을 통해 원본 데이터를 유지할 수 있다. 이를 immutable 하다고 표현한다. 

    //map : 원본 배열을 유지한채, 함수에서 정의한 방법대로 모든 원소를 가공해서 새로운 배열을 반환한다.
    //원본 배열에 대해 가격을 10배로 만드는 예제.
    var newData = data.map(function (v) {
        var obj = { title: v.title, content: v.content, price: v.price * 10 };
        return obj
    });
    
    
    //filter : 원본 배열을 유지한채, 함수에서 정의한 조건에 맞는 원소만 추려서, 새로운 배열을 반환한다.
    //가격이 5000 이상인 원소들만 추려서 새로운 배열을 만든다. 
    var newData2 = data.filter(function (v) {
        return v.price > 5000;
    });
    
    
    //filter와 map의 체이닝 : 가격이 5000이상인 애들의 가격을 문자열로 만들어준다. 
    var newData3 = data.filter(function (v) {
        return v.price > 5000;
    }).map(function (v) {
        var obj = { title: v.title, content: v.content, price: v.price + "" };
        return obj;
    });
    

    ✔️ 객체 리터럴과 this

    1️⃣ 객체 리터럴

     자바스크립트에서는 객체 리터럴이라는 표현식을 이용해 객체를 만들 수 있다. 

    var healthObj = {
      name : "달리기",
      lastTime : "PM10:12",
      showHealth : function() {
        console.log(this.name + "님, 오늘은 " + this.lastTime + "에 운동을 하셨네요");
      }
    }
    
    healthObj.showHealth();

    2️⃣ this 

     객체 안에서의 this는 그 객체 자신을 가리킨다. 참고로, ES6에서는 객체에서 메서드를 사용할 때 'function' 키워드를 생략할 수 있다.

    const obj = {
       getName() {
         return this.name;
         },
      setName(name) {
          this.name = name;
        }
    }
    obj.setName("crong");
    const result = obj.getName();

    this가 달라지는 경우 : 아래 코드는 1초뒤에 결과를 출력하는 예제이다. 하지만 setTimeout 함수는 비동기로 동작하므로 this에는 window 객체가 바인딩 되어서 제대로 동작하지 않는다. strict mode에서는 undefined가 바인딩된다. 

    var healthObj = {
      name : "달리기",
      lastTime : "PM10:12",
      showHealth : function() {
        setTimeout(function() {
            console.log(this.name + "님, 오늘은 " + this.lastTime + "에 운동을 하셨네요");      
        }, 1000)
      }
    }
    healthObj.showHealth();

    ◾ bind method : bind 함수는 새로운 함수를 반환하는 함수이다. bind 함수의 첫번째 인자로 this를 주어, 그 시점의  this를 기억하고 있는 새로운 (바인드된) 함수가 반환된다. ( 참고로 자바스크립트 함수는 '.' 을 통해 접근하는 순간 객체로 사용할 수 있다. 예를들어 function(){}.bind();는 function 네이티브 객체에 들어있는 bind 함수를 사용하는 것이다. )

    var healthObj = {
      name : "달리기",
      lastTime : "PM10:12",
      showHealth : function() {
        setTimeout(function() {
            console.log(this.name + "님, 오늘은 " + this.lastTime + "에 운동을 하셨네요");      
        }.bind(this), 1000)
      }
    }
    healthObj.showHealth();

    'Web Development > 부스트코스 - Front-End(JavaScript)' 카테고리의 다른 글

    [Front End] Javascript 기초  (0) 2020.03.05
    [Front End] CSS 기초  (0) 2020.03.05

    댓글

Designed by Tistory.