Why would you pass null to apply or call?

According to this JavaScript link :

The null value is a JavaScript literal representing a NULL value or an "empty" value, i.e. the value of the object is missing. This is one of the primitive meanings of JavaScript.

function getMax(arr){ return Math.max.apply(null, arr); } 

Wasn't the explicit passing of the this clearer, or at least more readable? Again, at this moment I cannot understand why you are using null .

+12
javascript
source share
5 answers

Call apply with a null value, because the first argument is similar to calling a function without providing any object for this .

What does the apply method do?

The apply() method calls a function with the given value this and arguments , represented as an array (or an object similar to an array).

 fun.apply(thisArg, [argsArray]) 

thisArg

The significance of this provided for pleasure. Note that this may not be the actual value that the method sees: if the method is a function in non-strict mode, null and undefined will be replaced with a global object and primitive values ​​will be placed in the field.

Further documentation can be found here .

+11
source share

Why would you pass null to apply or call?

If there is no value that you want to indicate for the this pointer inside the function, and the function you are calling does not expect a specific this value for proper operation.

Would not explicitly pass the this keyword? Or at least more human readable. And again at this point, I may not understand why you should use null.

In your particular case, it is probably best to pass a Math object:

 function getMax(arr){ return Math.max.apply(Math, arr); } 

While it turns out that it doesn't matter what you pass as the first argument to Math.max.apply(...) (just because of the specifics of the implementation of Math.max() ), passing Math sets the this pointer to exact the same thing that would be set when you usually call it as Math.max(1,2,3) , so this is the safest option, since you best simulate a normal call to Math.max() .

Why would you pass null to apply or call?

Here are some more details ... When using .call() or .apply() , null can be passed when you do not have a specific value that you want to set for the this pointer, and you know that the function you are calling does not expect that this has any specific meaning (for example, it does not use this in its implementation).

Note. Using null with .apply() or .call() usually only .call() with functions that are methods only for namespaces, and not object-oriented. In other words, the max() function is a method of the Math object only for reasons related to names, and not because the Math object has instance data that the .max() method must access.


If you did it like this:

  function foo() { this.multiplier = 1; } foo.prototype.setMultiplier = function(val) { this.multiplier = val; } foo.prototype.weightNumbers = function() { var sum = 0; for (var i = 0; i < arguments.length; i++) { sum += (arguments[i] * this.multiplier); } return sum / arguments.length; } var x = new foo(); x.setMultiplier(3); var numbers = [1, 2, 3] console.log(x.weightNumbers.apply(x, numbers)); 

When the method you call .apply() on needs to access the instance data, then you MUST pass the appropriate object as the first argument so that the method has the correct this pointer to do its work, as expected.

+10
source share

I was a bit late to answer this question. I will try to give a long descriptive explanation here.

What is null in JavaScript?

The null value is a literal (it cannot be a property of a global object such as undefined). This is one of the basic JavaScript values.

In APIs, null is often obtained at the place where an object can be expected, but the object does not matter.

fun.apply (thisArg, [argsArray])

thisArg . The value of this parameter is for entertainment. Please note that this may not be the actual value that the method sees: if the method is a function in the code of non-strict mode, then null and undefined will be replaced by a global object, and primitive values ​​will be placed in a box.

argsArray : an array-like object indicating the arguments to call fun with, or null or undefined if no arguments should be provided to the function. Starting with ECMAScript 5, these arguments can be a generic array type object, not an array. See below for browser compatibility information.

If you use "strict mode", then it is advisable to pass this or Math as a parameter.

+1
source share

One case where I found this useful is when the function I'm calling is already associated with a specific context.

Since related functions cannot be restored, and they will always be called with thisArg that was passed to bind , it makes no sense to pass thisArg to call or apply . From source :

The bind() function creates a new bound function (BF) .... When the bound function is called, it calls the [[Call]] internal method of [[BoundTargetFunction]] with the following Call(boundThis, args) arguments.

Here is an example:

 class C { constructor() { this.a = 1; } } function f(n, m) { console.log(this.a + n + m); } let c = new C(); var boundF = f.bind(c, 2); // the context 'c' is now bound to f boundF.apply(null, [3]); // no reason to supply any context, since we know it going to be 'c' 
+1
source share

Use is useful when you want to transfer responsibility for the execution of a function to a function defined at runtime and pass a variable number of arguments to that function. You may or may not have any appropriate “this” context when you do this.

For example, I use the library I wrote to make it easier to listen and call application events that apply.

I wanted to be able to raise an event like this:

 EventManager.raise('some:event-name', arg1, arg2, arg3, ..); 

... and so that all registered handlers for this event are called with this argument list (arg1, arg2, etc.). Thus, in the function of raising it passes through the handlers that are registered for this event name, and calls them, passing all the arguments passed, except for the name of the event, for example:

 var args = []; Array.prototype.push.apply(args, arguments); args.shift(); for (var l in listeners) { var listener = listeners[l]; listener.callback.apply(listener.context, args); } 

When a registered handler (listener.callback) is called, apply is used to pass a variable number of arguments. Here, I allowed the listener to provide this context for its event handler when the listener identifier is defined, but this context may not be defined or it may be null, and this is completely normal.

For a long time, the enhancement function did not even facilitate the use of the callback context. In the end, I came across a need, so I supported it, but in most cases I do not need or need to use it.

+1
source share

All Articles