Reputation: 2402
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 ??
Upvotes: 2
Views: 136
Reputation: 318468
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
.
Upvotes: 4
Reputation: 343
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.
Upvotes: 2