Three ideas at a Glance: Unknown five methods of declaring number in JS

Source: Internet
Author: User
Document directory
  •  
  • Method 2: var num = Number (123 );
  • Method 3: var num = new number (123 );

I chatted with a group of 90 young people who claimed to be Xiao Fang. It male had bad habits and talked about the technology. He suddenly asked

1. I can see three variables that declare a numerical value. What are the differences:

VaR num = 123; // method 1 var num = Number (123); var num = new number (123 );

2. method 1 is clearly a digital literal. For Mao, we can directly call various methods on the above, as shown below:

var num = 123;console.log(num.toString());

My mouth smiled:You are still young. I know at least five of the three types !!

With a smile, the mouth of the mouth began to twenty, and the forehead began to sweat: at least five kinds, yes,... What is the difference...

With the tolerance and pride of the old cainiao, I disdainfully said: I don't know. I will check the information myself... Turn around and start turningEcmas-1, 262(Fifth Edition)

 

I. Five Ways to declare numeric Variables
// Method 1: The most common method is to declare data using numbers literally.
VaR num = 123;
// Method 2: occasionally used. In most cases, convert a string to a number var num = Number (123 );
// Method 3: rarely used. God books, including rhino books, are listed in the not recommended var num = new number (123) method );
// Method 4: God mode. No one has ever used VaR num = new object (123 );
// Method 5: more bizarre, more strange var num = Object (123 );

As you can see, there are five declaration methods. method 1 is usually used like this. Method 3 to Method 5 is used for comparison. The following sections describe the following:

  1. What are the differences between the five declaration methods? What happened when you knocked on the Code with your trembling fingers?
  2. Method 1 is clearly not an object, but why can we call methods such as tostring on it?
Ii. Differences between various declarations Method 1: var num = 123;

Ec5 description:

A numeric literal stands for a value of the number type. this value is determined in two steps: first, a mathematical value (MV) is derived from the literal; second, this mathematical value is rounded as described below //.....

Summary:

  1. Parses the value of a variable, such as the integer and decimal part, because the numeric declaration method can also be num =. 123, num = 123e4, etc.
  2. Take an approximate value for the parsed value, such as num = 123. 33333333333333... 3333333333333333333333333. At this time, take the approximate value. If we take the approximate value, the rule is not expanded.
  3. The variable declared in this way is a simple numeric literal, not an object (as to why tostring and other methods can be called above, I will explain later)
Method 2: var num = Number (123 );

Ec5 description:

15.7.1 the number constructor called as a function

When number is called as a function rather than as a constructor, it performs a type conversion. 15.7.1.1 number ([value])

Returns a number value (not a number object) computed by tonumber (value) If value was supplied, else returns + 0.

Summary:

  1. In this example, the number is called as a common function instead of a constructor. Therefore, the returned value is not an object, but a simple value.
  2. The essence is the same as method 1. The difference from method 1 is that you need to execute different type conversion procedures for the type of input parameters and try to parse the parameters into corresponding values. The specific rules are as follows:

  

 

Method 3: var num = new number (123 ); Ec5 description:

15.7.2 the number Constructor

When number is called as part of a new expression it is a constructor: It initialises the newly created object. 15.7.2.1 new number ([value])

The [[prototype] internal property of the newly constructed object is set to the original number prototype object, the one that is the initial value of number. Prototype (15.7.3.1 ).

The [[Class] internal property of the newly constructed object is set to "number ".
The [[primitivevalue] internal property of the newly constructed object is set to tonumber (value) If value was

Supplied, else to + 0.

The [[extensible] internal property of the newly constructed object is set to true.
Summary:
  1. Number is called as the constructor. The returned value is a number-type object that can access the prototype attributes and methods of number. This may be confusing.
  2. VaR num = new number (123); console. log (typeof num); // output: objectconsole. log (object. prototype. tostring. call (Num); // output: [object number]
  3. The original value of the returned number type object ([[primitivevalue]) is the numeric value obtained after type conversion. The specific conversion rules are the same as those mentioned in method 2.
Method 4: VaR num = new object (123 ); Ec5 description:

15.2.2 the object constructor
When object is called as part of a new expression, it is a constructor that may create an object.

15.2.2.1 new object ([value])

When the object constructor is called with no arguments or with one argument value, the following steps are taken:

    1. If value is supplied, then
      A. If type (value) is object, then

      1. If the value is a native ecmascript object, do not create a new object but simply return value.

      2. If the value is a host object, then actions are taken and a result is returned in an implementation-dependent manner that may depend on the host object.

      B. if type (value) is string, return toobject (value ). c. if type (value) is Boolean, return toobject (value ). d. if type (value) is number, return toobject (value ).
    2. Assert: the argument value was not supplied or its type was null or undefined.

    3. Let OBJ be a newly created native ecmascript object.

    4. Set the [[prototype] internal property of obj to the standard built-in object prototype object (15.2.4 ).

    5. Set the [[Class] internal property of obj to "object ".

    6. Set the [[extensible] internal property of obj to true.

    7. Set all the internal methods of OBJ as specified in 8.12.

    8. Return obj.

  Personal Understanding:I posted a lot of text on it, which may be a headache, because New object (PARAM)In this way, variables are declared based on different types of input parameters, and the results are also different, for example, data types. Here, the Mask Body conversion rules are negligible. We only look at the section of our current relationship, that is, the above Highlighted in redThe main points of the text are:
  1. If a parameter is passed and the parameter is a number, an object of the number type is created and returned.Equivalent to method 3
  2. The value of this number object is equal to the passed parameter. The internal [[prototype] attribute points to number. prototype.
  Method 5: var num = Object (123 );

Ec5 description:

15.2.1 The object constructor called as a function

When object is called as a function rather than as a constructor, it performs a type conversion.

15.2.1.1 object ([value])

When the object function is called with no arguments or with one argument value, the following steps are taken:

  1. If value is null, undefined or not supplied, create and return a new object exactly as if the standard built-in object constructor had been called with the same arguments (15.2.2.1 ).

  2. Return toobject (value ).

Personal Understanding:
  1. When the input parameter is null, undefined, or null, it is equivalent to new object (PARAM), And Param is the parameter passed by the user.
  2. Otherwise, an object is returned. For the type of the object to be converted, see the following table. The specific example above is essentially equivalent to new number (123 ):

  

3. Simple Test Cases

VaR num = Object (123); console. Log (typeof num); // output: Object
Console. Log (object. Prototype. tostring. Call (Num); // output: [object number]
Iii. var num = 123; and VAR num = new number (123 );

Xianxianzhe warned us that it is best to use the first method. The reasons are as follows: low efficiency, and unexpected events may occur when eval (Num) occurs... Balabara

Aside from the above noises, we should pay attention to the following reasons:

VaR num = 123; console. Log (Num. tostring (Num); // output: '123', no error occurred.
Console. log (Num. tostring (); // output: '000000'. There was no error. -- In the case of surface deletion, a parameter num was mistakenly added to tostring. Thanks to Dino for pointing out :)
 

Doesn't it mean that the literal method declares only common numeric types, not objects? It is not scientific to call the tostring method of the object!

Okay, I checked the rhino book and found the answer:

When a user declares a variable literally and calls methods such as tostring on the variable, the JS Script Engine secretly creates the packaging object corresponding to the variable, and call the corresponding method on the object. When the call ends, the object is destroyed. This process is invisible to users, so many beginners may be confused about this.

Well, I admit that the above paragraph is not the original article, but my personal understanding of the corresponding section of the rhino book, In order to seem more professional and authoritative, I intentionally added a reference mark... The example above can be simply considered as the following process:

var num = 123;var tmp  = num;num = new Number(num);console.log(num.toString(num));num = tmp;

(Because the specification was turned over to 1 point last night, it was really difficult, so I was lazy. I believe the rhino book won't hurt me)

4. Post

Javascript variable declaration methods, type judgment, etc., have always been unable to speak out, the above content for beginners, is tantamount to destroying three views; even old cainiao like myself who have been with JavaScript for more than two years are often confused

Summary:

  1. Method 1 and method 2 are essentially the same
  2. Method 3, Method 4, and Method 5 are essentially the same

Last:

  If there are any mistakes or omissions in this example, please point out. If you think the article is useful to you, click "recommended"

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.