JavaScript: how an object is implemented in such a way that the new Object ({}) and Object ({}) are the same

In JavaScript, I can write:

x = new Object({ a: 3 })

and I will have x = { a: 3 }

Similarly, I can write

x = Object({ a: 3 })

and I will have again x = { a: 3 }.

My question is: how is it implemented Objectto satisfy both of these ways of calling it? In the first case, he will receive a new one this, and in the second he will receive a global object.

My best guess is something like:

var Object = function(obj) {
    var global = (function() { return this; })();
    if (global == this) { // I am called as a regular function
        // Create a copy of obj, potentially like this
        return { ...obj };
    } else { // I am called via new
        // Copy all fields of obj onto this
        // not sure what the best way to do this is.
    }
}
+4
source share
3 answers

Answer: in the specifier :

When the Object function is called with an additional parameter value, the following steps are performed:

  • NewTarget undefined, ,
    • ? OrdinaryCreateFromConstructor (NewTarget,% ObjectPrototype%).
  • null, undefined , ObjectCreate (% ObjectPrototype%).
  • ! ToObject ().

№1 , , -, Object, .

№ 2 , value, null undefined.

, 3 - , : ToObject , value , value , -op, , . new Object new Object({a: 1}) .

this, .

, Object this.

+4

,

function Object(obj) {
  return obj;
}
Hide result

, , window. , , , this.

, :

var a = {a : 3};
var b = new Object(a);
var c = Object(a);

console.log(a === b);
console.log(a === c);
Hide result

@user2357112 , , Object:

function Object(value) {
  if (typeof value === 'number') {
    return new Number(value);
  }
  
  if (typeof value === 'string') {
    return new String(value);
  }
  
  if (value === null || value === undefined) {
    return {};
  } 
  
  return value
}

var a = new Object(undefined);

console.log(new Object(1));
console.log(new Object('sad'));
console.log(new Object([]));
console.log(new Object({}));
console.log(new Object(null));
console.log(new Object());
Hide result
-1

I think this is something like

function Object(obj) {
  If (this instanceof Object) {
       return Object.assign(this, ...obj)
     }
  return new Object(obj);
 }
-1
source

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


All Articles