Applying a Function to Null in Javascript

老子叫甜甜 提交于 2019-11-27 14:10:59
jAndy

The first argument for Function.prototype.call is the context, which defines the this value for the execution context of the invoked function, nothing else.

So basically, you're saying that this is referring to null (at least, in ES5 strict mode), but since you don't access this anyway, it makes no difference.

In non-strict mode, this cannot be null, so it's replaced with the global object instead.

When you use .call or .apply with null or undefined, the default this (usually window) is automatically used instead if not in strict mode.

From MDN (emphasis mine):

thisArg
The value of this provided for the call to fun. Note that this may not be the actual value seen by the method: 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.

If you are in strict mode, it actually will be null or undefined.

(function() {
    'use strict';

    return this;
}).call(null); // null
(function() {
    'use strict';

    return this;
})(); // undefined

Its not. NULL in this case specifies to what object the this keyword is bound to. In your method, by setting it to NULL it will either not have a this variable binding or it will be bound to the function itself or the window.

Since you're not using any variables or functions that are accessed via this, then there's no need to use the call method ... you can just use sum(3,4)

As stated in, for example, MDN, the first argument is

The value of this provided for the call to [the method]. Note that this may not be the actual value seen by the method: 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.

As the MDN explained.

thisArg

The value of this provided for the call to fun. Note that this may not be the actual value seen by the method: 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.

Simply put it by a little code.

<script >
        'use strict'
        function fun() {
            alert(this);
        }
        fun.call(null);

    </script>

In the strict mode ,this is null. But in the not strict mode . this is window or global object.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!