Why can't Symbol be created with new in JS

Note that many basic data types of js can be created with new , but Symbol, as a new js data type, cannot be created in this way. Basic data types can be created with new to get wrapper objects instead of literals.

Similar to the difference between new String("hello") and "hello" in Java

This is a different point created with new , so it can be speculated that the official does not want us to get a packaging object of Symbol type. However, the wrapper object can still be obtained through the Object() method.
Here are some extensions:

The difference between creating an object with new and creating an object without new

In the MDN documentation we can see the following explanation:

  1. Create an empty simple JavaScript object (i.e. {});
  2. Add the attribute proto to the object newly created in step 1 , and link this attribute to the prototype object of the constructor;
  3. Use the newly created object in step 1 as the context of this ;
  4. If the function does not return an object, this is returned .

That is to say, new Foo() essentially calls the Foo() method, but the new keyword performs some additional operations on it. From this the next conclusion can be drawn:

How does Symbol know that we use the new keyword internally

There are many ways to judge whether to use new , here we assume that the Symbol() function is as follows:

function Symbol(){
    
    
	//native code here
	if(this instanceof Symbol){
    
    
		throw new Error('Uncaught TypeError: A is not a constructor')
	}
}

Since the new keyword will return an object, and __proto__ will point to the prototype object, an error will occur.
But only when the Symbol() method returns a value, its data type is the basic data type 'symbol'. Using instanceof requires at least the left operand to be an object type, so the return value is false and no error will be reported.

Guess you like

Origin blog.csdn.net/weixin_55658418/article/details/128802465