研究MDN Web文档上编写的find方法的polyfill,我没有遵循特定的行,让我共享代码
if (!Array.prototype.find) {
Object.defineProperty(Array.prototype, 'find', {
value: function(predicate) {
if (this == null) {
throw TypeError('"this" is null or not defined');
}
var o = Object(this);
var len = o.length >>> 0;
if (typeof predicate !== 'function') {
throw TypeError('predicate must be a function');
}
var thisArg = arguments[1];
var k = 0;
while (k < len) {
var kValue = o[k];
if (predicate.call(thisArg, kValue, k, o)) {
return kValue;
}
k++;
}
return undefined;
},
configurable: true,
writable: true
});
}
我的问题是表达式
var o = Object(this);
。代替var o = this
这样做的目的是什么?在上述两种情况下打印该值将返回相同的对象。这是
var o = new Object(this);
的缩写方式吗?我从方法中删除了注释以缩短文本,这是到polyfill实现的链接。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find#Polyfill
谢谢!
最佳答案
在严格模式下,this
并不总是对象。 Object(this)
确保o
是对象,而不是基元。
这是this
是原始语言的示例:
"use strict";
Object.defineProperty(String.prototype, "nishCap", {
writable: true,
configurable: true,
value() {
console.log(typeof this); // "string"
const o = Object(this);
console.log(typeof o); // "object"
return o.substring(0,1).toUpperCase() + o.substring(1);
}
});
const capped = "foo".nishCap();
请注意,这甚至适用于数组方法,因为您可以在非数组上调用它们,例如
Array.prototype.find.call("foo", ch => ch === "o")
。这是
var o = new Object(this);
的缩写方式吗?不,
new Object
始终创建一个新对象(并且不使用您为其提供的参数)。当您call Object
as a function时,它将其参数强制为object。因此,原始字符串成为String
对象,原始数字成为Number
对象,依此类推。代替
var o = this
这样做的目的是什么?该polyfill紧跟the spec,其开头为:
让O成为? ToObject(此值)。
在大多数情况下,这并不重要,但是如果在某些极端情况下将其遗弃会导致可观察到的行为与规格有所差异,我也不会感到惊讶。
关于javascript - JavaScript中Object(this)的目的是什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58971294/