하루5분코딩"함수 메소드"

HwangSoonhwan·2020년 10월 18일
0

### 이글을 읽기전 꼭! 먼저 읽어보셔야합니다!

apply()

func.apply(thisArg,[argsArray])

  • thisArg : func을 호출하는데 제공되어질 this의 값

  • argsArray : func이 호출되어야 하는 인수를 지정하는 유사배열 객체

let arr = [1,2,3,4];
Math.max(1,2,3,4) // 4
but!! math.max(arr) // NaN
그렇기 때문에 apply를 사용해준다.
Math.max.apply(null , arr)// null의 위치는 어떤값이든 상관없다.

✓배열형태를 정수 나열 형태로 만들어 준다.

call()

func.call(thisObj,arg1,arg2...)

  • thisObj : func 호출에 제공되는 this의 값(생략가능)
  • arg1,arg2... : func이 호출되어야 하는 인수
let list = {
  name: 'Harry'
}
let list2 = {
  name: 'jack'
  study: function() {console.log(this.name + '이 학교를 등교했습니다.');}
}
---------------------------------
list2.study(); //'jack이 학교를 등교했습니다.'
list2.study.call(list)//'Harry이 학교를 등교했습니다.' 
//list2를 호출했지만 매개변수를 list를 넣어주어 list를 가리킨다.

또 다른 사용법

let list = document.queryselectorAll('a'); // a 태그를 전부다 가져온다
function getIdElement(element){
 return element.id;
}
-list.map(getIdElement) // 오류-
Array.prototype.map.call(list, getIdElement);// map은 배열 내장함수이기 때문에 call을 사용하여 map을 사용할수 있다.

✓Apply 와 Call 사용시 주의점!

function list(a, b, c) {
  console.log(a + b + c)
}
list(1, 2, 3)//6
list.call(null, 1, 2, 3) //6 
list.apply(null , [1, 2, 3]) //6

bind()

새롭게 바인딩한 함수를 만드는 것

let list = {
  name: 'Harry'
}
let list2 = {
  name: 'jack'
  study: function() {console.log(this.name + '이 학교를 등교했습니다.');}
}
let student = list2.study.bind(list);
student(); //'Harry이 학교를 등교했습니다.' 

활용

function Box (w,h) {
  this.width = w;
  this.heigth = h;
  ----------------
  this.getArea = function(){
    return this.width * this.heigth;
  }
  ----------------
  this.printArea = function(){
    console.log(this.getArea());
  }
}
   ---------------
let box1 = new Box(100 , 50)'//instance 만들기
box1.printArea() // 5000
setTimeout(box1.printArea, 1000)//1초 뒤에 오류가 난다 왜??? this 값이 변하기 때문이다!
setTimeout(box1.printArea.bind(box1), 1000)//1초뒤에 5000 이 잘 출력된다.

bind() 커링

function template(name , money){
  return '<h1>'+ name + '</h1><span>' + money + '</span>';  
}
let template = template.bind(null,'steve');
template(100) 	// <h1>steve</h1><span>100</span>
profile
👨‍🍳요리사의 "쿠킹" 스토리가 아닌 "코딩" 스토리💻

0개의 댓글