fn.apply with first param null or undefined

 

Questions


I am confused with fn.apply. For example,

Consider this snippet

Array.min = function(){
    return Math.min.apply( Math, arr );
}

I can grasp this. I understand fn.apply as,

Calls a function with a given this value and arguments provided as an array

But the below snippets also work

Array.min = function(){
    return Math.min.apply( null, arr );
}

Array.min = function(){
    return Math.min.apply( undefined, arr );
}

MDN explains this as,

if the method is a function in non-strict mode code, null and
undefined will be replaced with the global object, and primitive
values will be boxed

I don’t really understand the part which I have made bold. What is the meaning of that statement? Could anyone elaborate a bit?

 

 

————————————————-

Answer

The “global object” is the global object. Just read the spec:

The unique global object is created before control enters any execution context.

In addition to the properties defined in this specification the global object may have additional host defined properties. This may include a property whose value is the global object itself; for example, in the HTML document object model the window property of the global object is the global object itself.

In the browser, you’re essentially calling Math.min.apply(window, arr), which you can verify:

(function() {
    console.log(this);  // Logs `Window {...}`
}).apply(undefined);

This is one of the many problems with non-strict mode. this sometimes becomes window, and you silently end up creating global properties. In strict mode, this will truly be undefined:

(function() {
    'use strict';

    (function() {
        console.log(this);  // Logs `undefined`
    }).apply(undefined);
})();

“Primitive values will be boxed” just says that primitives like numbers and strings will be “boxed” into a container object because primitives themselves are not objects. Again, you can verify this:

(function() {
    console.log(this);  // Logs `Number {}`, not `2`
}).apply(2);

Here’s some more info on primitives: Why are JavaScript primitives not instanceof Object?

javascript

Leave a Reply

Your email address will not be published. Required fields are marked *