Does it make sense to use .apply( ) and pass the same instance as context?

后端 未结 2 1051
天涯浪人
天涯浪人 2021-01-22 10:09

I\'m reading Javascript Web Applications, from O\'Reilly. At various points in the book, the author uses something along the following:

instance.init.apply(insta         


        
2条回答
  •  广开言路
    2021-01-22 10:22

    The point is that arguments is an array-like object. Doing ...

    instance.init(arguments);
    

    ... passes one argument, which is an array-like object containing certain arguments. On the other hand, doing ...

    instance.init.apply(instance, arguments);
    

    ... will pass the array-like object as separate arguments. It is true that setting instance is kind of useless because you already wrote it, but if using .apply you simply need to set the this value as well.

    A quick example of the difference:

    function log(a, b, c) {
        console.log(a, b, c);
    }
    
    function log2() {
        log.apply(null, arguments); // `this` value is not meaningful here,
                                    // it's about `arguments`
    }
    
    function log3() {
        log(arguments);
    }
    
    log(1, 2, 3);  // logs:  1, 2, 3
    
    log2(1, 2, 3); // logs:  1, 2, 3
    
    log3(1, 2, 3); // logs:  , undefined, undefined
                   //        where  contains the values 1, 2, 3
    

提交回复
热议问题