[英]I have no idea Object(this) means
In https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/fill 在https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/fill
there is a line like 有一条线就像
// Steps 1-2.
if (this == null) {
throw new TypeError('this is null or not defined');
}
var O = Object(this); // <- WHAT IS THIS???????????
// Steps 3-5.
var len = O.length >>> 0;
// Steps 6-7.
var start = arguments[1];
var relativeStart = start >> 0;
// Step 8.
var k = relativeStart < 0 ?
Math.max(len + relativeStart, 0) :
Math.min(relativeStart, len);
// Steps 9-10.
var end = arguments[2];
var relativeEnd = end === undefined ?
len : end >> 0;
// Step 11.
var final = relativeEnd < 0 ?
Math.max(len + relativeEnd, 0) :
Math.min(relativeEnd, len);
// Step 12.
while (k < final) {
O[k] = value;
k++;
}
// Step 13.
return O;
and I can't find any necessity to assign O as Object(this). 我找不到将O指定为对象的必要性(this)。
Is it written just for readability or is there any specific reason for assigning? 它是为了可读性而编写的还是有任何特定的分配原因?
As suggested in the comments on the code, this section is to accurately pollyfill the first steps documented in the spec . 正如对代码的评论中所建议的那样,本节将准确地对规范中记录的第一步进行pollyfill。
- Let O be ToObject(this value).
设O为ToObject(此值)。
- ReturnIfAbrupt(O).
ReturnIfAbrupt(O)。
Though a bit out-of-order, this is performing the fucntion of ToObject(this value)
: 虽然有点无序,但这是执行
ToObject(this value)
的功能:
var O = Object(this);
Basically, if it is called on a non-object, the non-object should be cast to an Object
. 基本上,如果在非对象上调用它,则应将非对象强制转换为
Object
。
For example, if we were to run this bit of mostly-nonsensical code in a JavaScript engine which natively supports this method, we would see a Number
object instance gets returned. 例如,如果我们在本机支持此方法的JavaScript引擎中运行这些大多数无意义的代码,我们会看到返回一个
Number
对象实例。
Array.prototype.fill.call(123);
That line would ensure the same result from the polyfill. 该线将确保来自polyfill的相同结果。
The Object constructor returns its argument when the argument is already an object. 当参数已经是对象时,Object构造函数返回其参数。 If it's not an object, it returns the "objectified" version of the argument: a String instance if it's a string, a Number instance if it's a number, etc.
如果它不是一个对象,它返回参数的“objectified”版本:一个String实例,如果它是一个字符串,一个Number实例,如果它是一个数字,等等。
The function in question is a little weird, and in particular the value of this
will usually be an object anyway. 有问题的功能是有点怪异,特别的价值
this
通常是一个对象呢。 It doesn't have to be, but you kind-of have to go out of your way to get to the innards of the polyfill with a this
value that isn't an object. 它没有要,但你有种,有走出自己的方式去用的填充工具的内脏
this
值是不是一个对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.