ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Call / Bind / Apply
    개발/Javascript 2022. 6. 6. 23:42

    *복습 자료라서 뻔한 내용은 생략

     

     

    Summary.

     

    1. call() allows for a function/method belonging to one object to be assigned and called for a different object

        + apply()와 다른 부분은 두번째 인자로 arguments list를 받는지, single array를 받는지 차이

        + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call

    function greet() {
      const reply = [this.animal, 'typically sleep between', this.sleepDuration].join(' ');
      console.log(reply);
    }
    
    const obj = {
      animal: 'cats', sleepDuration: '12 and 16 hours'
    };
    
    greet.call(obj);  // cats typically sleep between 12 and 16 hours

     

    2. With apply(), you can write a method once, and then inherit it in another object, without having to rewrite the method for the new object.

        + this refers to the current object (the calling object)

        + With apply, you can write a method once, and then inherit it in another object, without having to rewrite the method for the new object.

        + argument 개수가 많으면 limit을 넘겨서 에러 발생 가능하므로 개수 파악 중요

        + (다음에) 왜 push, min과 같은 아래 연산이 전체 element에 자동으로 적용되는 것?

    //concat과 달리 existing array에 추가됨
    const array = ['a', 'b'];
    const elements = [0, 1, 2];
    array.push.apply(array, elements);
    console.info(array); // ["a", "b", 0, 1, 2]
    // min/max number in an array
    const numbers = [5, 6, 2, 3, 7];
    
    // using Math.min/Math.max apply
    let max = Math.max.apply(null, numbers);
    // This about equal to Math.max(numbers[0], ...)
    // or Math.max(5, 6, ...)
    
    let min = Math.min.apply(null, numbers);
    
    // vs. simple loop based algorithm
    max = -Infinity, min = +Infinity;
    
    for (let i = 0; i < numbers.length; i++) {
      if (numbers[i] > max) {
        max = numbers[i];
      }
      if (numbers[i] < min) {
        min = numbers[i];
      }
    }

     

    3. bind() returns a copy of the given function with the specified this value, and initial arguments (if provided).

        + The bind() function creates a new bound function, which is an exotic function object (a term from ECMAScript 2015) that wraps the original function object. Calling the bound function generally results in the execution of its wrapped function.

    this.x = 9;    // 'this' refers to global 'window' object here in a browser
    const module = {
      x: 81,
      getX: function() { return this.x; }
    };
    
    module.getX();
    //  returns 81
    
    const retrieveX = module.getX;
    retrieveX();
    //  returns 9; the function gets invoked at the global scope
    
    //  Create a new function with 'this' bound to module
    //  New programmers might confuse the
    //  global variable 'x' with module's property 'x'
    const boundGetX = retrieveX.bind(module);
    boundGetX();
    //  returns 81
    function list() {
      return Array.prototype.slice.call(arguments);
    }
    
    function addArguments(arg1, arg2) {
      return arg1 + arg2;
    }
    
    const list1 = list(1, 2, 3);
    //  [1, 2, 3]
    
    const result1 = addArguments(1, 2);
    //  3
    
    // Create a function with a preset leading argument
    const leadingThirtySevenList = list.bind(null, 37);
    
    // Create a function with a preset first argument.
    const addThirtySeven = addArguments.bind(null, 37);
    
    const list2 = leadingThirtySevenList();
    //  [37]
    
    const list3 = leadingThirtySevenList(1, 2, 3);
    //  [37, 1, 2, 3]
    
    const result2 = addThirtySeven(5);
    //  37 + 5 = 42
    
    const result3 = addThirtySeven(5, 10);
    //  37 + 5 = 42
    //  (the second argument is ignored)
    // By default within setTimeout(), the this keyword will be set to the window 
    // (or global) object. When working with class methods that require this to 
    // refer to class instances, you may explicitly bind this to the callback function,
    // in order to maintain the instance.
    
    function LateBloomer() {
      this.petalCount = Math.floor(Math.random() * 12) + 1;
    }
    
    // Declare bloom after a delay of 1 second
    LateBloomer.prototype.bloom = function() {
      window.setTimeout(this.declare.bind(this), 1000);
    };
    
    LateBloomer.prototype.declare = function() {
      console.log(`I am a beautiful flower with ${this.petalCount} petals!`);
    };
    
    const flower = new LateBloomer();
    flower.bloom();
    //  after 1 second, calls 'flower.declare()'

     

    

    Additional.

    1. (다음에) bind() 사용 예시 중 shortcut 이해하기

        + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind#creating_shortcuts

     

     

    Reference.

    '개발 > Javascript' 카테고리의 다른 글

    Web API  (0) 2022.06.18
    Client Side Storage  (0) 2022.06.07
    Class  (0) 2022.06.06
    Object Model  (0) 2022.06.06
    Map, Set  (0) 2022.06.06
Designed by Tistory.