What is the purpose of doing `Object (this)`?

I went through the implementation of Array findpolyfill in MDN:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find?v=control#Polyfill

Copy it below:

  // https://tc39.imtqy.com/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 new 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 new 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;
      }
    });
  }

Why do we need to do var o = Object(this);?

What does it do Object(this)?

Thanks for any discussion.

+4
source share
2 answers

This is an interesting question ... Thanks for the message!

Honestly, I am a little surprised Object(this), because JavaScript seems to force something on the object (using wrappers) in situations where it thiscould potentially be a primitive value.

this Function.prototype.bind(), JavaScript ( ):

var foo = function () {
  console.log(this, typeof this);
}.bind('foo');

var bar = function () {
  console.log(this, typeof this);
}.bind(1337);

var baz = function () {
  console.log(this, typeof this);
}.bind(false);

var qux = function () {
  console.log(this, typeof this);
}.bind(NaN);

var quux = function () {
  console.log(this, typeof this);
}.bind(undefined);

var corge = function () {
  console.log(this, typeof this);
}.bind(null);

var grault = function () {
  console.log(this, typeof this);
}.bind([]);

var garply = function () {
  console.log(this, typeof this);
}.bind({});

var waldo = function () {
  console.log(this, typeof this);
}.bind(/regex/);

var fred = function () {
  console.log(this, typeof this);
}.bind(function () {});

foo(); // String { 0: "f", 1: "o", 2: "o" } object
bar(); // Number { 1337 } object
baz(); // Boolean { false } object
qux(); // Number { NaN } object
quux(); // Window object
corge(); // Window object
grault(); // Array [ ] object
garply(); // Object { } object
waldo(); // /regex/ object
fred(); // function fred<() function   

this Function.prototype.call() Function.prototype.apply(), JavaScript :

Array.prototype.foo = function () {
  console.log(this, typeof this);
};

['foo'].foo(); // Array [ "foo" ] object
Array.prototype.foo.call('bar'); // String { 0: "b", 1: "a", 2: "r"} object
Array.prototype.foo.call(42); // Number { 42 } object
Array.prototype.foo.call(true); // Boolean { true } object
Array.prototype.foo.call(NaN); // Number { NaN } object
Array.prototype.foo.call(undefined); // Window object
Array.prototype.foo.call(null); // Window object
Array.prototype.foo.call({}); // Object { } object
Array.prototype.foo.call(/regex/); // /regex/ object
Array.prototype.foo.call(function () {}); // function () function

JavaScript , , , . Number, String Boolean :

var num = 1337,
    str = '',
    bool = true;
    
console.log(Number(str), typeof Number(str));
console.log(Number(bool), typeof Number(bool));

console.log(String(num), typeof String(num));
console.log(String(bool), typeof String(bool));

console.log(Boolean(num), typeof Boolean(num))
console.log(Boolean(str), typeof Boolean(str));
Hide result

Object():

console.log(typeof Object(false), Object(false) instanceof Boolean);
console.log(typeof Object('bar'), Object('bar') instanceof String);
console.log(typeof Object(42), Object(42) instanceof Number);
console.log(typeof Object(NaN), Object(NaN) instanceof Number);
console.log(typeof Object(undefined), Object(undefined) instanceof Object);
console.log(typeof Object(null), Object(null) instanceof Object);
console.log(typeof Object(['foo']), Object(['foo']) instanceof Array);
console.log(typeof Object({}), Object({}) instanceof Object);
console.log(typeof Object(/regex/), Object(/regex/) instanceof RegExp);
console.log(typeof Object(function () {}), Object(function () {}) instanceof Function);
Hide result

, Object(this) this -. this , :

var obj1 = {baz: 'Baz'},
    obj2 = Object(obj1);

var arr1 = ['foo', 'bar'],
    arr2 = Object(arr1);
    
var reg1 = /regex/,
    reg2 = Object(reg1);
    
var fun1 = function () { return 'Hello!'; },
    fun2 = Object(fun1);
    
console.log(arr1 === arr2);
console.log(obj1 === obj2);
console.log(reg1 === reg2);
console.log(fun1 === fun2);
Hide result

, Object , , , new :

var foo = Object('foo'),
    bar = new Object('bar');
    
console.log(foo);
console.log(bar);
Hide result

, , : , this , Object(this) . , , .

?


torazaburo : - ! , this ! , , Object(this)...

Function.prototype.bind()

var foo = function () {
  'use strict';
  console.log(this, typeof this);
}.bind('foo');

var bar = function () {
  'use strict';
  console.log(this, typeof this);
}.bind(1337);

var baz = function () {
  'use strict';
  console.log(this, typeof this);
}.bind(false);

var qux = function () {
  'use strict';
  console.log(this, typeof this);
}.bind(NaN);

var quux = function () {
  'use strict';
  console.log(this, typeof this);
}.bind(undefined);

var corge = function () {
  'use strict';
  console.log(this, typeof this);
}.bind(null);

var grault = function () {
  'use strict';
  console.log(this, typeof this);
}.bind([]);

var garply = function () {
  'use strict';
  console.log(this, typeof this);
}.bind({});

var waldo = function () {
  'use strict';
  console.log(this, typeof this);
}.bind(/regex/);

var fred = function () {
  'use strict';
  console.log(this, typeof this);
}.bind(function () {});

foo(); // foo string
bar(); // 1337 number
baz(); // false boolean
qux(); // NaN number
quux(); // undefined undefined
corge(); // null object
grault(); // Array [ ] object
garply(); // Object { } object
waldo(); // /regex/ object
fred(); // function fred<() function

Function.prototype.call()

Array.prototype.foo = function () {
  'use strict';
  console.log(this, typeof this);
};

['foo'].foo(); // Array [ "foo" ] object
Array.prototype.foo.call('bar'); // bar string
Array.prototype.foo.call(42); // 42 number
Array.prototype.foo.call(true); // true boolean
Array.prototype.foo.call(NaN); // NaN number
Array.prototype.foo.call(undefined); // undefined undefined
Array.prototype.foo.call(null); // null object
Array.prototype.foo.call({}); // Object { } object
Array.prototype.foo.call(/regex/); // /regex/ object
Array.prototype.foo.call(function () {}); // function () function
+3

this .

Object(this) .

:

const array = Array.prototype;

Object.defineProperty(array, 'foo1', { value() { 
  return this.length >>> 0;  }});

Object.defineProperty(array, 'foo2', { value() { 
  "use strict"; 
  return this.length >>> 0; }});

console.log(Array.prototype.foo1.call(undefined));
console.log(Array.prototype.foo2.call(undefined));
Hide result

0, undefined . , undefined , , this.length .

MDN:

, this , (a.k.a. "boxed" )

null undefined:

if (this == null) {
  throw new TypeError('"this" is null or not defined');
}

, . , - .

+4

Source: https://habr.com/ru/post/1677579/


All Articles