1

I stumbled upon such usage in Array.prototype.includes() polyfill code:

var O = Object(this);

What are the semantics of this function? Links to documentation would be welcome too.

3

1 Answer 1

5

The Object constructor, when called as a function, attempts to convert the argument to an object, as follows:

  • If the argument is already an object, it returns it.
  • If the argument is object-coercible (boolean, number, string or symbol), it coerces it to an object.
  • If the argument is null or undefined, or no argument is passed, it returns a new ordinary object that inherits from Object.prototype. Like if you used ({}).

Examples:

var obj = [1,2,3], symb = Symbol();

// Object argument
Object(obj);    // obj;

// Object-coercible argument
Object(true);   // Boolean { [[BooleanData]]: true }
Object(1234);   // Number  { [[NumberData]]: 1234 }
Object("ab");   // String  { [[StringData]]: "ab", 0: "a", 1: "b", length: 2 }
Object(symb);   // Symbol  { [[SymbolData]]: symb }

// Non-object-coercible argument
Object(null);   // Object {  }
Object(void 0); // Object {  }
Object();       // Object {  }

The polyfill uses Object(this) because the spec says Array.prototype.includes should use ToObject, but that's an internal thing which is not exposed to JS code.

Sign up to request clarification or add additional context in comments.

2 Comments

I wonder why this use case was omitted at developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…. Is this use case quite rare?
@SlavaSt It's explained. Well, it says that it doesn't matter whether you call or instantiate it, but there is a difference if you instantiate it via a subclass.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.