簡體   English   中英

沒有new關鍵字或.create方法的Object()

[英]Object() without the new keyword or .create method

我在MDN上尋找Array.prototype.includes()的polyfill,然后遇到以下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(...)將傳遞的值轉換為對象。 如果它已經是一個對象,它將簡單地返回值本身,否則wit將創建一個新對象並將其返回。

規格

當Object作為函數而不是構造函數調用時,它將執行類型轉換。

例:

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

在這種情況下,這樣做的目的是什么?

它確保該值是一個對象,而不是基元。 實現僅遵循規范

  1. 讓O成為? ToObject(此值)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM