没有new关键字或.create方法的对象()

Object() without the new keyword or .create method

本文关键字:对象 方法 create new 关键字 没有      更新时间:2023-09-26

我正在MDN上寻找Array.prototype.includes()的多边形,我遇到了下面的Object()语法:

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;
  };
}

Object(this)在做什么?在这种情况下,this的目的是什么?

Object(...)将传递的值转换为对象。如果它已经是一个对象,它只返回值本身,否则wit将创建一个新对象并返回它。

从规格:

当Object作为函数而不是构造函数调用时,它执行类型转换。

的例子:

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

在这种情况下这样做的目的是什么?

确保值是对象,而不是原语。实现遵循规范:

  1. 让O成为?ToObject(这个值)。