Home > Web Front-end > JS Tutorial > A brief overview of five unknown ways to declare Number in JS_javascript skills

A brief overview of five unknown ways to declare Number in JS_javascript skills

WBOY
Release: 2016-05-16 17:41:43
Original
1228 people have browsed it

I was chatting with a cute 90-year-old young man in the group who called himself Xiao Fangfang. I talked about the bad habits of IT men and got involved in technology. Xiao Fangfang suddenly asked
1. Declare a variable of numerical type. I saw Three types, what are the differences:

Copy code The code is as follows:

var num = 123; //Method 1
var num = Number(123);
var num = new Number(123);

2. Method 1 is obviously a numerical literal, which is normal for us Various methods can be called directly on it, as follows:
Copy code The code is as follows:

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

I smiled slightly: Young man, you are still a bit young. There are not only three kinds, but I know at least five. kind! !
Smiling and smiling, the corners of his mouth began to twitch, and cold sweat began to break out on his forehead: There are at least five kinds, yes, but. . . What's the difference. . .
With the unique reserve and pride of an old rookie, I said disdainfully: I don’t know this, just look up the information myself. . . Turn around and start flipping through ECMAS - 262 (fifth edition)

1. Five ways to declare numeric type variables
Copy code The code is as follows:

//Method 1: The most common way, declare through numeric literals
var num = 123;
//Method 2: Occasionally used, in most cases to convert strings into numbers
var num = Number(123);
//Method 3: Rarely used, various sacred books, including Rhinoceros Books have listed it as a non-recommended method
var num = new Number(123);
//Method 4: God’s method, I haven’t seen anyone use it yet
var num = new Object(123) );
//Method 5: More bizarre and weird
var num = Object(123);

As you can see, among the above five declaration methods, method one needless to say, it is usually used like this; method three to method five are used for comparison, which will be explained separately below:
1.5 What is the difference between the two declaration methods? What happened when you typed the code with your trembling fingers?
2. What is declared in method 1 is obviously not an object, but why can we usually call methods on it, such as toString, etc.?

2. The difference between various declaration methods
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
//....Personal summary summary:
1. Parse the value of the variable, such as taking out the integer part, decimal part, etc., because the number declaration method can also be in the form of num = .123, num = 123e4, etc.
2. Approximate the parsed value, For example, num = 123.33333333333333...33333333333333333333333333.... At this time, it is necessary to take the approximate value. If the specific approximation is taken, the rules will not be expanded
3. The variable declared in this way is just a simple numerical literal, not Object (as to why toString and other methods can be called on it, we will explain it 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. Personal summary summary:
1. Here Number is just called as an ordinary function, not a constructor, so what is returned is not an object, but A simple value
2. The essence is the same as method 1; the difference from method 1 is that different type conversion processes need to be performed based on the type of the incoming parameter to try to parse the parameter into the corresponding value. 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.personal Summary summary:
1. The Number function constructor is called here, and an object of type Number is returned. This object can access the prototype properties and methods of Number; this may be a bit confusing, and I will talk about it later
Copy code The code is as follows:

var num = new Number(123);
console.log( typeof num); //Output: object
console.log(Object.prototype.toString.call(num)); //Output: [object Number]

3. The original value ([[PrimitiveValue]]) inside the returned Number type object is the numerical value obtained after type conversion. The specific conversion rules are consistent with 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 :
There is a lot of text posted above, which may give you a headache, because through new Object(param) declares variables in this way. The results obtained will be different depending on the specific type of the parameters passed in, such as the data type. The specific conversion rules here can be ignored. We only look at the part of our current relationship, that is, the text marked in red above. The key points are:
1. If a parameter is passed, and the parameter is a number, create and return a Number type object - yes, it is actually equivalent to method three
2. The value of the Number object is equal to the passed parameter, and the internal [[prototype]] attribute points to Number.prototype
Method five: 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 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 parameter passed in is empty, undefined or null, it is equivalent to new Object (param), param is the parameter passed in by the user
2. Otherwise, an object is returned. As for the specific conversion into The object type can be seen in the table below; specifically for the above example, it is essentially equivalent to new Number(123):

3. Simple test case
Copy code The code is as follows:

var num = Object(123);
console.log(typeof num); //Output: object console.log(Object.prototype.toString.call(num)); //Output: [object Number]

3. var num = 123; and var num = new Number( 123);
The sages and sages have warned us that it is best to use the first method. The reason is very convincing: it is inefficient and unexpected situations may occur when eval(num) is used. . . Balabala
Putting aside the noise above, what we want to focus on here is why the following statement will not go wrong:
Copy code The code is as follows:

var num = 123;
console.log(num.toString(num)); //Output: '123', no error occurred

Didn’t it mean that the literal declaration is just an ordinary numerical type, not an object? But the toString method call does not come from the object. This is unscientific!
Okay, I checked the Rhinoceros book and found the answer:
When the user declares a variable through literals and calls methods such as toString on the variable, the JS script engine will Secretly create a packaging object corresponding to the variable, and call the corresponding method on the object; when the call is completed, the object is destroyed; this process is invisible to the user, so many beginners will have this problem Puzzled.

Okay, I admit that the above paragraph is not the original text, it is just my personal understanding of the corresponding paragraph in the Rhinoceros book, and I deliberately added a quotation mark in order to appear more professional and authoritative. . . The example given above can be simply viewed as the following process:
Copy code The code is as follows:

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

(Because I was flipping through the standard last night until almost 1 o'clock, I was really sleepy, so I was lazy. I believe Rhino Book will not trick me)

4. Write it at the back
I have always felt unable to complain about Javascript’s variable declaration method, type judgment, etc. The above content is tantamount to ruining the outlook for beginners; even for someone like me who has been working with Javascript for two years Many veteran rookies are often confused
A brief summary:
1. Method one and method two are essentially the same
2. Method three, method four and method five are essentially the same
The last Finally:
If there are any errors or omissions in the examples in the article, please point them out; if you think the article is useful to you, you can click "Recommend" :)
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template