How to implement apply pattern in Javascript

前端 未结 3 1475
刺人心
刺人心 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条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-06 11:54

    I'm not aware of any design patterns named The Apply Pattern so I don't really think this is at all related to design patterns. However, there is an apply method of function objects in javascript (along with the corresponding call method) so I'll be explaining those.

    The apply and call methods basically allow an object to "steal" a method from another object. You see, in javascript, methods are bound very-very late: at invocation time. Only when a method is called is the value of 'this' resolved. In a normal method call:

    some_object.do_something();
    

    the 'this' keyword in do_something refers to some_object. Apply and call lets you re-assign 'this'. For example:

    some_object.do_something.apply(another_object);
    

    the 'this' keyword in do_something now refers to another_object. So you're calling the do_something method belonging to some_object on another_object.

    Now, this is interesting and all but why would anyone want to do this? Here's a concrete example of why this is useful:

    // say you want to get some DIVs in the document, you can get all of them with:
    var some_divs = document.getElementsByTagName('DIV');
    
    // say you want the third to fifth DIV in the document, some_divs looks like an
    // array so you might think you can slice it, but it's not. It's a collection
    // of elements that fakes being an array and doesn't implement the slice method.
    
    // No worries, we can steal the slice method from an array 
    // and apply it to some_divs:
    var wanted_divs = [].slice.apply(some_divs,[2,5]);
    
    // Alternatively:
    var wanted_divs = [].slice.call(some_divs,2,5);
    

    There is another use case for apply which is a result of the difference between how apply and call works. If you have all your arguments in an array and the function expects individual arguments you can use apply to pass the array and have the function see the content of the array as individual arguments:

    function some_function (first,second) {
        alert(first+second);
    }
    var argument_array = ['hello','world'];
    some_function.apply(null, argument_array);
    

提交回复
热议问题