Javascript Function: Apply Application

I was shocked by this oddity.

Let's say I have this array:

var array = [{ something: 'special' }, 'and', 'a', 'bunch', 'of', 'parameters']; 

Could I apply method of the function to call the function with this object {something: 'special'} , and the rest of the parameters array ?

In other words, can I do it

 var tester = function() { console.log('this,', this); console.log('args,', arguments); }; tester.apply.apply(tester, array); 

And expect the conclusion to be next?

 > this, {"something": "special"} > args, {"0": "and", "1": "a", "2": "bunch", "3": "of", "4": "parameters"} 

I tried.

 TypeError: Function.prototype.apply: Arguments list has wrong type 

But why? It seems like this should work.

+6
source share
2 answers

But why?

Step-by-step reduction of your calls:

 tester.apply.apply(tester, array) // resolves to (Function.prototype.apply).apply(tester, array) // does a tester.apply({something: 'special'}, 'and', 'a', 'bunch', 'of', 'parameters'); 

Here you can see what is going wrong. It would be right

 var array = [ {something: 'special'}, ['and', 'a', 'bunch', 'of', 'parameters'] ]; 

then apply.apply(tester, array) will become

 tester.apply({something: 'special'}, ['and', 'a', 'bunch', 'of', 'parameters']); 

which makes

 tester.call({something: 'special'}, 'and', 'a', 'bunch', 'of', 'parameters'); 

So, with your original array you will need to use

 (Function.prototype.call).apply(tester, array) 
+11
source

The apply method takes one argument for the this context and one argument for the arguments you want to apply. The second argument must be an array.

 tester.apply.apply(tester, array); 

Because of the second method, apply the first one will be called like this:

 tester.apply({something: 'special'}, 'and', 'a', 'bunch', 'of', 'parameters'); 

And since 'and' is not an array, you get the TypeError that you described. You can easily fix this using the call method:

 tester.call.apply(tester, array); 

call will take separate arguments instead of an array, which will produce the desired result.

0
source

Source: https://habr.com/ru/post/949598/


All Articles