2

I'm Collecting JavaScript Classes prototypes that make it compatible to old browsers never mind of that but what i wonder while collecting them that the Developer At Mozila comparing the Array to null i can see that is non since but maybe I'm wrong and there is an explanation for that ???

 if (!Array.prototype.every) {
    Array.prototype.every = function(fun /*, thisp */) {
        "use strict";

        if (this == null)
            throw new TypeError();

        var t = Object(this);
        var len = t.length >>> 0;
        if (typeof fun != "function")
            throw new TypeError();

        var thisp = arguments[1];
        for (var i = 0; i < len; i++) {
            if (i in t && !fun.call(thisp, t[i], i, t))
                return false;
        }

        return true;
    };
}

at this line

 if (this == null)

this is refers to the Array

This code at Mozila

Kindly i need an explanation is that a logic to compare a Array to a null even if i know that "this" which is refer to a must array type not a variable can be array or null ?? what you think ??

2 Answers 2

4

It could happen when someone calls it without a context, e.g. Array.prototype.every(...) instead of someArray.every(...). Or a more likely case: Passing someArray.every as a callback to some other function which will then invoke it without the proper context.

Since the function is running in Strict Mode this === undefined when no context is provided. And undefined == null.

Sign up to request clarification or add additional context in comments.

Comments

2

It's useful for cases like:

Array.prototype.every.call(null, ...);

You are not likely to meet that version of code, but in place of null can be a variable, that is not yet initialized, for example. In that case TypeError is only logical.

1 Comment

You are missing the most important detail. Normally, when you pass null to .call (or .apply), this will refer to window. Test: (function() { console.log(this); }.call(null));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.