Fn.apply With First Param Null Or Undefined
Solution 1:
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?
Solution 2:
if the method is a function in non-strict mode code, null and undefined will be replaced with the global object
i.e. 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, i.e. in case of fn.apply(2, args)
the variable this
inside fn
will refer to a Number Object whose value will be 2.
Post a Comment for "Fn.apply With First Param Null Or Undefined"