How to implement apply pattern in Javascript

前端 未结 3 1474
刺人心
刺人心 2021-02-06 11:04

What is apply invocation pattern in Javascript in reference to function invocation patterns and how can I use it? What are the benefits of using this invocation pattern.

3条回答
  •  萌比男神i
    2021-02-06 12:04

    The use of apply is related to the function context (the this keyword) and argument passing.

    First, I think you should know in which cases the this keyword is implicitly set:

    1- When a function is called as a method (the function is invoked as member of an object):

    obj.method(); // 'this' inside method will refer to obj
    

    2- A normal function call:

    myFunction(); // 'this' inside the function will refer to the Global object
    // or 
    (function () {})();
    

    3- When the new operator is used:

    var obj = new MyObj(); // this will refer to a newly created object.
    

    Here is when apply and call come, those methods let you set explicitly the context when you invoke a function, eg.:

    function test(a) {
      alert(this + a);
    }
    
    test.call('Hello', ' world!');
    

    In the above code, when the test function is called setting the this keyword to a String ('Hello'), and passing the a argument (' world.').

    Both, call and apply change the context of the executing function (the this keyword) inside the called function, but the difference between them is that with apply, you can send an Array or an Array-like object as the arguments of the function to be executed, which is extremely useful, for example:

    function sum() {
      var result = 0;
      for (var i = 0; i < arguments.length; i++) {
        result += arguments[i];
      }
      return result;
    }
    
    var args = [1,2,3];
    sum.apply(null, args); // will return 6
    

    That can avoid some very hacky, bad (and common) eval calls like:

    eval('sum(' + args.join() +')');
    

    Another example, the Math.max and Math.min methods, those methods can receive an arbitrary number of arguments like:

    var max = Math.max(2,4,6,8); // 8
    

    But what if you have an Array of numbers?

    var numbers = [2,4,6,8];
    numbers.push(10);
    var max = Math.max.apply(null, numbers); // 10
    

    Also note that when null or undefined is used as the this argument with call or apply, the this object will refer to the Global object (similar to the case #2, normal function invocation).

    For the Math.max example, the context is not really relevant, since they are just like "static" methods, the this keyword is not used internally...

提交回复
热议问题