Applying a Function to Null in Javascript

旧时模样 提交于 2019-12-28 04:04:28

问题


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?


回答1:


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.




回答2:


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



回答3:


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)




回答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.




回答5:


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.



来源:https://stackoverflow.com/questions/11659134/applying-a-function-to-null-in-javascript

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