Devoid Design Devoid Design - 2 months ago 11
Javascript Question

Object() without the new keyword or .create method

I was looking on MDN for a polyfill for Array.prototype.includes() and I came across the Object() syntax below:

if (!Array.prototype.includes) {
Array.prototype.includes = function(searchElement /*, fromIndex*/) {
'use strict';
if (this == null) {
throw new TypeError('Array.prototype.includes called on null or undefined');
}
//This is the line in question
var O = Object(this);
var len = parseInt(O.length, 10) || 0;
if (len === 0) {
return false;
}
var n = parseInt(arguments[1], 10) || 0;
var k;
if (n >= 0) {
k = n;
} else {
k = len + n;
if (k < 0) {k = 0;}
}
var currentElement;
while (k < len) {
currentElement = O[k];
if (searchElement === currentElement ||
(searchElement !== searchElement && currentElement !== currentElement)) { // NaN !== NaN
return true;
}
k++;
}
return false;
};
}


What is Object(this) doing and what is the purpose of this in this case?

Answer

Object(...) converts the passed value to an object. It simply returns the value itself if it is already an object, otherwise wit will create a new object and return that.

From the spec:

When Object is called as a function rather than as a constructor, it performs a type conversion.

Example:

var obj = Object("foo");
// same as 
// var obj = new String("foo");

what is the purpose of this in this case?

It ensures that the value is an object, not a primitive. The implementation just follows the spec:

  1. Let O be ? ToObject(this value).
Comments