함수를 실행할 수 있는 다양한 방법들이 있습니다.

  • function(함수) 호출
  • method(메소드) 호출
  • new 키워드를 이용한 constructor(생성자) 호출 : 객체지향프로그래밍(OOP)
  • 함수 메소드 Function.prototype.call(), Function.prototype.apply() 이용: 특히, 유사배열(Array-like object)에 대하여 Array.prototype의 메소드를 빌려서 이용하는 것이 가능하게 됩니다.

한편, Function.prototype.bind() 는 .call()/.apply()와 다르게 함수를 바로 실행시키지 않고, this가 바인딩된 함수를 반환합니다.

function add(x, y) {
  this.val = x + y;
  console.log(this.val);
}
const obj = { val: 0 };
/* apply, call */
add.apply(obj, [2, 8]); // 10
add.call(obj, 2, 8);    // 10
/* bind */
const boundFn = add.bind(obj, 2, 8);
boundFn(); // 10

특히, Function.prototype.bind()의 경우 특정 함수가 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());
  };
}
const b = new Box(100, 50);
b.printArea(); // 5000

/* bind()를 이용하여 b.printArea의 this를 명시 */
setTimeout(b.printArea.bind(b), 2000); // 2초 후 b.printArea() 실행

<서버 요청>

fetch('http://서버주소/weather?q=Seoul')
.then(function(resp) {
  // 응답 형식에 따라 resp.text() 가 될 수도 있다
  return resp.json();
})
.then(function(json) {
  console.log(json); // { tempature: 27 }
});

<서버 기록>

let newPost = {
  "userId": 1,
  "title": "새 글을 써봤습니다",
  "body": "안녕하세요?"
}
fetch('http://서버주소/posts', {
  method: 'POST',
  body: JSON.stringify(newPost)
}).then(function(resp) {
  return resp.json();
}).then(function(json) {
  console.log(json); // { id: 123 }
});

코드 및 자료 출처: 코드스테이츠(CodeStates)

0개의 댓글