简体   繁体   中英

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?

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM