Javascript 在Array.prototype.find';在我们的实现中,为什么需要使用Objetct(this)来转换为对象?

Javascript 在Array.prototype.find';在我们的实现中,为什么需要使用Objetct(this)来转换为对象?,javascript,Javascript,在中,为什么需要使用Object(this)将this转换为对象 // https://tc39.github.io/ecma262/#sec-array.prototype.find if (!Array.prototype.find) { Object.defineProperty(Array.prototype, 'find', { value: function(predicate) { // 1. Let O be ? ToObject(this value).

在中,为什么需要使用
Object(this)
this
转换为对象

// https://tc39.github.io/ecma262/#sec-array.prototype.find
if (!Array.prototype.find) {
  Object.defineProperty(Array.prototype, 'find', {
    value: function(predicate) {
      // 1. Let O be ? ToObject(this value).
      if (this == null) {
        throw TypeError('"this" is null or not defined');
      }

      var o = Object(this);

      // 2. Let len be ? ToLength(? Get(O, "length")).
      var len = o.length >>> 0;

      // 3. If IsCallable(predicate) is false, throw a TypeError exception.
      if (typeof predicate !== 'function') {
        throw TypeError('predicate must be a function');
      }

      // 4. If thisArg was supplied, let T be thisArg; else let T be undefined.
      var thisArg = arguments[1];

      // 5. Let k be 0.
      var k = 0;

      // 6. Repeat, while k < len
      while (k < len) {
        // a. Let Pk be ! ToString(k).
        // b. Let kValue be ? Get(O, Pk).
        // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)).
        // d. If testResult is true, return kValue.
        var kValue = o[k];
        if (predicate.call(thisArg, kValue, k, o)) {
          return kValue;
        }
        // e. Increase k by 1.
        k++;
      }

      // 7. Return undefined.
      return undefined;
    },
    configurable: true,
    writable: true
  });
}
//https://tc39.github.io/ecma262/#sec-array.prototype.find
if(!Array.prototype.find){
Object.defineProperty(Array.prototype,“find”{
值:函数(谓词){
//1.设O为?ToObject(该值)。
if(this==null){
抛出类型错误(“'this'为空或未定义”);
}
var o=对象(此);
//2.设len为?ToLength(?Get(O,“length”))。
var len=o.length>>>0;
//3.如果IsCallable(谓词)为false,则抛出TypeError异常。
if(类型谓词!=='function'){
抛出类型错误('谓词必须是函数');
}
//4.如果提供了thisArg,则T为thisArg;否则T为未定义。
var thisArg=参数[1];
//5.设k为0。
var k=0;
//6.当k
大多数情况下,因为规范中这么说

为什么会这样呢?因为稍后,它会访问值的属性(如
.length
[k]
),该值必须是该值的对象。当然,polyfill中使用的成员访问语法已经可以为我们做到这一点,但是在spec文本中,Get算法需要一个对象,并且到一个对象的转换应该只发生一次,而不是在每个成员访问上(尽管这是无法区分的)

为什么要将任意值转换为对象?因为方法可以使用原语值调用,就像
这个
参数一样-不寻常但可能。正如说明书所说

注意:
find
函数是有意通用的;它不要求其此值是
数组
对象。因此,它可以被转移到其他类型的对象中用作方法

例如:

String.prototype.find = Array.prototype.find;
console.log("test".find(x => x > 'f' && x < 't'))
String.prototype.find=Array.prototype.find;
console.log(“test.find”(x=>x>'f'&&x<'t'))

使用
Array.prototype.find.call(“test”,console.log)”可以观察到这种差异。
如果没有这一行,它将是一个字符串原语,而有了这一行,它就是一个字符串对象(如规范所述)。