TIL(20.03.09)

TheJang·2020년 3월 9일
0

TIL

목록 보기
11/33

코드스테이츠 4주차 #1

<회고> 동기,비동기 javascript에서의 this 5가지 사용법, 함수 메소드 bind, call, apply에 대해 알아 보았다. 동기 비동기에 대한 개념은 신세계였고 this를 객체의 인스턴스로만 사용하는 줄 알았지만 javascript는 다른 언어와 다르게 다양한 사용법이 있다는것도 알게 되었다. 다만 오늘 너무 많은 것을 배우다 보니 완벽히 소화 하지는 못했다.

< 오늘 배운 것들 >😄

  • 동기, 비동기
  • this 사용법
  • 함수의 메소드 bind, call, apply
  • 서버에 요청하는 방법

1. this

this의 메소드 작동 패턴 5가지

  • Global: window -> 전역객체
  • function 호출 :window -> 함수 내부에서의 this
  • Method호출: 부모 obj -> 객체 내부에서의 this
  • construction mode -> instance로서의 this
  • .call, .apply, .bind -> 함수 메소드로서의 this

Global객체로서의 thisdhk function으로서의 this는

2. 함수 메소드 (call, apply, bind)

1) call

특징: 함수메소드의 call 사용은 nodelist가 함수메소드 사용을 가능하게 해준다.

function moreThanFive(element){
  return element.length > 5; 
}

let arr = ['code', 'states'];
arr.filter(moreThanFive);  // 인스턴스 arr이 먼저 등장 , 메소드 filter가 뒤에 등장

//['states']
Array.prototype.filter.call(arr,moreThanFive);
// ['states']

유사배열에 적용 케이스

let list = document.querySelectorAll('li')

Array.prototype.filter.call(list, function(elementLi) {
  return elementLi.classList.contains('selected');
});

메소드를 먼저 기술하고, 그 뒤에 인스턴스 (this인자를) 넘겨줌으로 해결 할 수있다.

2) apply

call 과 유사하지만 파라미터가 배열형이다.

let arr = [12,44,55,66]

Math.max.apply(null,arr); // 여기서 null값은 this이다.
// 66

apply로 처리

function moreThanFive(element){
  return element.length > 5; 
}

let arr = ['code', 'states'];
arr.filter(moreThanFive);  // 인스턴스 arr이 먼저 등장 , 메소드 filter가 뒤에 등장

Array.prototype.filter.apply(arr, [moreThanFive]) 

call과 다르게 파라미터를 배열 값으로 주어 처리한다.

3) Bind

  • setTimeout을 사용한 bind
function Box(w,h) {
    this.width = w;
    this.height = h;
    
    this.getArea = function() {
        return this.width * this.height;
    }
    
    this.printArea = function() {
        console.log(this.getArea());
    }
}

let b = new Box(100,50);
b.printArea(); //5000

setTimeout(b.printArea.bind(b),2000); //this값을 인스턴스 b로 지정해야한다.

  • 커링
function template(name, money) {
  return '<h1>' + name + '</h1><span>' + money + '</span>';
}

template('yoonjangwon' , 1000)
// <h1>yoonjangwon</h1><span>1000</span> 결과 값

let yoonjangwon = template.bind(null, 'yoonjangwon') ;

yoonjangwon(500);

// <h1>yoonjangwon</h1><span>500</span> 결과 값

커링: 인자를 하나만 받아주어 재사용이 가능하게 할수있다.

profile
어제보다 오늘 더 노력하는 프론트엔드 개발자

0개의 댓글