analogcoding

call & apply & bind 본문

Study JS for me/Keyword

call & apply & bind

be well 2019. 4. 27. 17:42

function protoype methods

 

call,apply 는 그냥 함수가 실행되도록 "도와"주는 것이고 bind 는 "새로운" 함수를 "만들어" 준다.

 

함수를 호출하는 2가지 방법

call,apply는 함수를 실행시킨다(=호출해 실행한다).

사용하는 이유는  call,apply메서드의 첫번째 인수 때문이다.
call,apply는 첫번째 인수 없이도 에러 없이 작동한다. 인수가 없을 경우, 자동적으로 전역객체를 가리키게 된다.

 

function.prototype.call

 

call은 함수를 빌려오거나 프로퍼티를 가져올 수 있다.

  • case-1. 함수를 빌려오는 경우
  • case-2. 프로퍼티를 빌려오는 경우
  • case-3. Array.prototype.slice.call/apply.(obj/arguments)
function.call(thisArg,arg1,arg2,...)

 

function.prototype.apply

function.apply(thisArg,[argsArray])

여기서 thisArg 는 this가 바라보는 객체이고 뒤에 따라오는 arg1,arg2 나 [argsArray] 는 각 arguments 를 
call 에 경우 하나 씩 인자로 받고 apply 의 경우 하나의 배열로 받는다.

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

var obj = {
   val: 0
};

add.call(obj,2,8); // call의 경우 this.val 인 obj를 바라보고 2 와 8 을 각 요소로 받아 10을 리턴.
console.log(obj.val) // => 10

add.apply(obj,[2,8]); // call의 경우 this.val 인 obj를 바라보고 2 와 8 을 배열로 받아 10을 리턴.
console.log(obj.val) // => 10
var obj = {
  string : 'origin' ,
  foo: function(){
    console.log(this.string);
  }
}

obj.foo() // => 'origin'

// 여기서 this.string은  obj의 내부 함수인 foo를 실행하는데 이 때 foo의 부모인 obj의 string인 
// 'origin'을 바라본다.

var obj2 = {
  string : 'what?'
}

obj.foo.call(obj2); // => 'what?'

// foo 함수에 call로 obj2를 this가 바라보게 해서 this.string이 obj2에 string인 'what?'을 바라본다.

 


call 의 활용

function getMax() {

  var argsArray = Array.prototype.slice.call(arguments);
  
  var maxValue = argsArray.reduce(function(acc,curr)
  return (acc > curr) ? acc : curr 
  });
  return maxValue;
  }
  
  // arguments를 배열의 값으로 복사해서 인자로 받는 값들을 활용한다.
  
  console.log(getMax(4,5,2,7,3)); // => 7
function Product(name,price) {
  this.name = name;
  this.price = price;
  this.print = function() {
    console.log(this.constructor.name + ':' + this.name + ':' + this.price);
    }
}

function Food(name,price){
  Product.call(this,name,price);
  this.category = 'food';
}

var cheese = new Food('pizza',5);
// Food함수에 인자로 pizza , 5를 받아서 Food내에 this로 그 값을 그대로 Product함수에 인계해서
// cheese.print() 에서 print함수 this가 바라보는 Product에 인자로 pizza 와 5 가 전달된다.
// cheese.print() => Food:pizza:5 
// cheese => Food {name: "pizza", price: 5, print: ƒ, category: "food"} 

apply 의 활용

var min = Math.min(7,35,2,8,21);
console.log(min); // => 2

var arr = [5,1,2,3,33];
var min2 = Math.min.apply(null, arr);
console.log(min2); // => 1

bind 

 

인자로 넘겨준 객체와 연결(bind)된 새로운 함수를 반환.

callback 함수를 특정 객체와 연결하고 싶을 때 사용한다.

fn.bind(thisArg[,arg1[,arg2[, ...]]])

thisArg : 바인딩 함수가 this로 사용할 값. 바인딩 함수를 new 연산자로 생성한 경우 무시됩니다.

arg1,arg2 : 바인딩한 함수가 원본 함수에 차례대로 제공할 매개변수.

 

인자로 넘겨준 객체와 연결된 새로운 함수를 반환한다.

function foo() {
 return this;
}

var bindFoo = foo.bind({a:1});


foo() // => window
bindFoo(); // => {a:1}

bind의 경우  정의가 확실하게 되지 않아서 추가로 복습해서 자료를 추가할 예정!

'Study JS for me > Keyword' 카테고리의 다른 글

Template literals  (0) 2019.05.11
ES6 : let , const  (0) 2019.05.10
Execution context 와 This  (0) 2019.04.26
Closure  (0) 2019.04.23
Scope [global , local] / Hoisting  (0) 2019.04.23
Comments