简体   繁体   中英

fn.apply with first param null or undefined

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?

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?

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

ie window in case of browsers, I am not sure what it refers to in case of nodejs,

and primitive values will be boxed

primitive values will be wrapped into their corresponding Objects, ie in case of fn.apply(2, args) the variable this inside fn will refer to a Number Object whose value will be 2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM