본문 바로가기
창고(2021년 이전)

[JS] 함수메소드(Function Methods)

by 측면삼각근 2019. 10. 13.
728x90
반응형

함수를 실행하는 다양한 방법

  • function(method)호출
  • new 키워드를 이용한 호출
  • 함수 메소드 .call .apply를 이용
//.call .apply 복습

function add(x, y){
	this.val = x + y;
    console.log(this.val);
}

let obj = { val : 0 };

add.apply(obj, [2, 8]); // 10
add.call(obj, 2, 8);//10

 


.bind


// call/ apply와는 다르게, 함수를 바로 실행시키지 않고, this 값이 바인딩된 함수를 리턴한다.

function add(x, y){
	this.val = x + y;
    console.log(this.val);
}

let obj = { val:0 };

let boundFn = add.bind(obj, 2, 8); // boundFn은 함수
boundFn(); // 10, add 는 여기에서됨
//일반적인 function(method) 호출처럼 보이지만, this값이 obj로 이미 바인딩되어있다.

 


apply case

let arr = [7, 35, 2, 8, 21 ];

// 이 배열 중 가장 작은 값을 Math.min을 이용해 얻어내려면?

let minimum = Math.min.apply(null,arr);
// 여기에선 this 의 의미가 없으므로 null로 넘겨도 된다.
// Math는 construcotr가 아니므로 실행context도 없다.
console.log(minimum);

 

 


call / apply case

call 또는 apply를 이용해 주체가 되는 인스턴스와 메소드의 순서를 바꿀 수 있다.

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

let arr = ['code', 'states'];

// 인스턴스 arr 이 먼저 등장하고 메소드 filter가 뒤에 등장한다.
arr.filter(moreThanFive);
// ['states']

// 메소드(filter)가 먼저등장하고, 인스턴스 (arr)를 나중에 넣는다.
Array.prototype.filter.call(arr, moreThanFive);
// ['states']

// 주어와 동사가 바뀌는 느낌으로 이해하면 편햐다.

 

 


 

call case

배열 메소드를 유사배열(array - like object)에 적용시키고자 할 때 사용 할 수 있다.
※ 유사배열 - 자료형은 배열처럼 보이지만, 일반적인 배열 메소드를 사용 할 수 없다.

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

let list = document.querySelectorAll('li');
//유사배열

Array.prototype.filter.call(list, function(elementLi){
	return elementLi.classList.contains('selected');
    //filter의 첫번째 인자인 콜백함수를 두번째 인자로 넘김
});




//혹은

function getElementId(element){
	return element.id;
}

list.map(getElemnetId);
//에러

Array.prototype.map.call(list, getElementId);

 


bind case : 특정함수가 this 값을 바꿔버리는 경우

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, 2000); //2초 후 b.printArea를 실행
// 실행시 this.getArea is not a function 에러
// 그렇다면 this의 값은 무엇인가? - window이다.

// setTimeout에는 함수를 인자로 넘겨야 하며, (함수 실행이 아닌)

this 값이 window로 들어가지 않도록 명시적으로 this값을 인스턴스 b로 지정해야 한다.

setTimeout(b.printArea.bind(b), 2000);
//2초 후 b.printArea를 실행

setTimeout의 경우, 인자로 넘기는 함수 this값은, 기본적으로 window 객체가 바인딩 된다.

 

 


 

bind case : currying (커링)

currying : 인자 여러개를 받는 함수를, 인자 하나를 받는 함수로 바꾸는 방법

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

let tmplSteve = template.bind(null, 'Steve');
templSteve(100); //<h1>Steve</h1><span>100</span>

let tmplJonny = template.bind(null, 'Jonny');
tmplJonny(500); //<h1>Jonny</h1><span>500</span>
tmplJonny(1000); //<h1>Jonny</h1><span>1000</span>

//tmplSteve 함수의 name 파라미터에는 'Steve'라는 값이 이미 바인딩 되어있다.
// template 이라는 함수에는 this 값을 사용하지 않으므로, 다른 특별한 값을 넣어줄 필요가 없다.

 

반응형

'창고(2021년 이전)' 카테고리의 다른 글

[JS] 템플릿 리터럴 : `${}` - Template literals  (0) 2019.10.25
[JS] 화살표 함수 => Fat Arrow Function  (0) 2019.10.25
[JS] 비동기 호출  (0) 2019.10.08
[JS] this  (0) 2019.10.07
[JS] DOM(Document Object Model)  (0) 2019.10.03