没有 new 关键字或 .create 方法的 Object() [英] Object() without the new keyword or .create method

查看:44
本文介绍了没有 new 关键字或 .create 方法的 Object()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

if (!Array.prototype.includes) {Array.prototype.includes = function(searchElement/*, fromIndex*/) {'使用严格';如果(这个 == 空){throw new TypeError('Array.prototype.includes call on null or undefined');}//这是有问题的行var O = Object(this);var len = parseInt(O.length, 10) ||0;如果 (len === 0) {返回假;}var n = parseInt(arguments[1], 10) ||0;无功k;如果 (n >= 0) {k = n;} 别的 {k = len + n;如果 (k <0) {k = 0;}}var currentElement;而 (k < len) {currentElement = O[k];if (searchElement === currentElement ||(searchElement !== searchElement && currentElement !== currentElement)) {//NaN !== NaN返回真;}k++;}返回假;};}

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

解决方案

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

来自规范:

<块引用>

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

示例:

var obj = Object("foo");//和...一样//var obj = new String("foo");

<块引用>

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

它确保该值是一个对象,而不是一个原始值.实现只是遵循规范:

<块引用>

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

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

这篇关于没有 new 关键字或 .create 方法的 Object()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆