Applying a Function to Null in Javascript

2019-01-11 15:11发布

Why does the following work:

function sum(a,b) { return a + b; }
var result = sum.call(null,3,4);     // 7

Why is result defined? I am invoking sum as a method of null. But null is not an object and cannot have properties!

What is going on?

5条回答
对你真心纯属浪费
2楼-- · 2019-01-11 15:42

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)

查看更多
欢心
3楼-- · 2019-01-11 15:42

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.

查看更多
看我几分像从前
4楼-- · 2019-01-11 15:47

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.

查看更多
爷、活的狠高调
5楼-- · 2019-01-11 15:51

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.

查看更多
forever°为你锁心
6楼-- · 2019-01-11 15:54

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
查看更多
登录 后发表回答