Constructor built-in functions in Javascript

When I do this:

var person = new Object(); person.name = "alex"; console.log(person) 

:

 Object { name="alex"} 

However, let's say I drop the β€œnew” word and do:

 var person = Object(); person.name = "alex"; console.log(person) 

Conclusion also:

 Object { name="alex"} 

Why?

+4
source share
2 answers

Because some built-in functions are just defined to act in this way. For example, see ES5 15.2.1.1 for Object :

15.2.1.1 Object ([value])

When the Object function is called with no arguments or with a single parameter value, the following steps are performed:

  • If null , undefined or not specified, create and return a new Object in the same way as if the standard built-in Object constructor was called with the same arguments ( 15.2.2.1 ).
  • Return ToObject(value) .

They check whether they were called with new or not, and if they do not act as if they were called with new .

Not all designers work like that. For example, Date will return a string when called without new .


You can implement this yourself:

 function Foo() { if(!(this instanceof Foo)) { return new Foo(); } // do other init stuff } 

Foo() and new Foo() will act the same way (it gets more complicated with variable arguments, though).

+4
source

Since your example is a built-in function of type Object, and, as indicated above, it is similar for this type, it does not work in the same way for most other built-in functions, such as Number (). You must be very careful when calling them with the keyword "new" or not. Because by default the keyword 'new' with the constructor of the function returns an object, not a primitive type directly. Thus, you cannot, for example, check the strict equality of two variables, one of which is declared and assigned using new Number() , and the other with Number()

An example would be:

 var num1 = Number(26); var num2 = new Number(26); num1 == num2; // returns true num1 === num2; // returns false 

You can check the difference in the console log:

 console.log(num1); > 26 console.log(num2); > Number {26} > __proto__: Number > [[PrimitiveValue]]: 26 
0
source

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


All Articles