Types of variables in JavaScript

Source: Internet
Author: User

About types

What is a type? Simply put, a type is to assign a binary sequence in the memory to some meaning. For example, binary Sequence 0100 0000 0111 0000 0001 0101 0100 1011 1100 0110 1010 0111 1110 1111 1001 if it is regarded as a 64-bit unsigned integer, It is 1110, and according to the binary representation rules stipulated by IEEE 4643234631018606494 (see Appendix 1) the Double Precision Floating Point type is 257.331.

Variable type: most computer languages use variables to store and represent data. Some languages specify a type for variables in the entire program (whether at compile time or runtime ), this type cannot be changed. In contrast, JavaScript and other language variables can store any type, and they use non-type variables. Whether the variable type exists is not related to the syntax. For example, the var type variable is also provided in C #. However, the following statement will cause an error in C:

var a=1;a="string";

The reason is that the var keyword of C # Only omits the variable type declaration and automatically infers the variable type according to the initialization expression. Therefore, the var variable of C # still has a type. In JavaScript, you can assign any value to a specific variable at any time, so JavaScript variables are of no type.

Strong type and weak type: according to the design method of the computer language type system, there are two types: strong type and weak type. The difference between the two lies in whether implicit conversion can be performed transparently between different types during computing. From the user's point of view, if a language can implicitly convert all its types, its variables and expressions are involved in the operation, even if the type is incorrect, implicit conversions can also be used to obtain the correct type, which is called a weak type for users as if all types can perform all operations. In contrast, the type of a strong-type language does not necessarily have implicit conversion (for example, C ++ is a strong-type language, but double and int in C ++ can be converted to each other, however, the double and any type of pointer must be forcibly converted)

Why is there a type? Type can help programmers write the correct program, which is embodied as a constraint in the process of actually writing the program. The general rule is that the more constraints, the less error-prone, but the more difficult it is to write programs. Variables have the strongest type language constraints. Typical examples are C ++. The weak type language constraints of variables are the weakest. Typical examples are JavaScript. In JavaScript, this error is often caused by weak constraints:

var a =200;var b ="1";var c= a + b;  

You may expect c to be 201, but it is actually "2001". This error will never occur in strong-type languages. However, JavaScript does not have these constraints, so it is easy to splice numbers and string types. Therefore, constraints and flexibility are always a set of features that need to be balanced for Language designers.

Static type and dynamic type: type is a constraint that works through type check. In different languages, type check works in different stages, which can be divided into compile-time check and runtime check. For interpreted languages such as JavaScript, there are also stages similar to the compilation process, that is, lexical analysis and syntax analysis, if the type check of interpreted language is completed in the syntax analysis or earlier stage, it can also be considered similar to the compile-time check. So it is more reasonable to say static type check and dynamic type check.

Interestingly, many languages check the type during compilation, but its type information can still be obtained at runtime. For example, in C #, metadata is used to save the type information. In the runtime stage, you can obtain and use the type information through reflection.

JavaScript gives priority to flexibility in all aspects of design, so it uses dynamic type checks, and JavaScript does not actively check the type except for a few specific operations. You can get the type information of any variable or expression at runtime and check its correctness through program logic.

Types specified by JavaScript standards

The JavaScript Standard specifies nine types: Undefined Null Boolean String Number Object Reference List Completion

Among them, the three types of Reference List Completion are only used during language parsing and cannot be directly accessed from the program. We will not introduce them here. The following six types are available:

  • Undefined type
  • The Undefined type has only one undefined value, which is the value when the variable is not assigned a value. In JS, The Global object has an undefined attribute to indicate undefined. In fact, undefined is not a JavaScript keyword, you can assign a value to the global undefined attribute to change its value.

  • Null type
  • The Null type has only one null value, but JavaScript provides it with a keyword null to indicate this unique value. The meaning of Null type is "an empty object reference ".

  • Boolean Type
  • Boolean can be set to true or false.

  • String type
  • The formal interpretation of the String type is a 16-bit unsigned integer sequence, which is actually used to represent text information encoded in UTF-16.

  • Number Type
  • JavaScript has a total of 18437736874454810627 (264-253 + 3) values. The Number of JavaScript is stored as a double-precision floating point, except that 9007199254740990 represents NaN. It complies with IEEE 754 (see Appendix 1) and occupies 64-bit 8 bytes.

  • Object Type
  • The most complex type in JavaScript is the Object, which is an unordered collection of a series of attributes. Function is the Object that implements the private attribute [call, the JavaScript host can also provide some special objects.

Types in JavaScript user eyes:

I have discussed the types specified in JS standards. However, one problem that cannot be ignored is that JS standards are written to JS implementers. For JS users, the types do not have to be defined according to standards, for example, because Javascript is running. during operation, the non-Object type is automatically converted to the corresponding Object, so "str ". length and (new String ("str ")). length is equivalent. From this point of view, it is considered that the two belong to the same type. We can use some language features in JS to identify the type during running, but the results of these methods are different. You need to decide whether it is good or bad.

Typeof -- looks very official: typeof is an operator in JS language. From its literal point of view, it is obviously used to obtain the type, according to the JavaScript standard, typeof gets the string representation of the variable type name. It may produce 6 types of results: string, bool, number, undefined, object, function, in addition, the JavaScript standard allows its implementers to customize the typeof values of some objects.

The JS standard has the following description list:

Type Result
Undefined "Undefined"
Null "Object"
Boolean "Boolean"
Number "Number"
String "String"
Object (native and doesn' t implement [[call]) "Object"
Object (native and implements [[call]) "Function"
Object (host) Implementation-dependent

The following example is from Rimifon of 51js. It shows how typeof in IE produces "date" and "unknown:

var xml=document.createElement("xml"); var rs=xml.recordset; rs.Fields.Append("date", 7, 1); rs.Fields.Append("bin", 205, 1); rs.Open(); rs.AddNew(); rs.Fields.Item("date").Value = 0; rs.Fields.Item("bin").Value = 21704; rs.Update(); var date = rs.Fields.Item("date").Value; var bin = rs.Fields.Item("bin").Value; rs.Close(); alert(date); alert(bin); alert([typeof date, typeof bin]); try{alert(date.getDate())}catch(err){alert(err.message)}  

There are many criticisms about this method that is closest to the semantic judgment of "type". One of them is that it cannot distinguish different objects, new String ("abc ") it cannot be distinguished from the use of typeof new Number (123). In JS programming, a large Number of objects are often used, while typeof can only give one fuzzy result "object" to all objects ", this greatly reduces its practicality.

Instanceof -- prototype or type? The meaning of instanceof is translated into Chinese as "Yes ...... It is a Class-oriented Object-Oriented Programming term. JS does not actually provide support for class-based programming at the language level. Although the JavaScript standard is not mentioned, the design and operator settings of some built-in objects imply an "official" implementation class method, that is, to use functions as classes, when the new operator acts on a function, it sets the prototype attribute of the function as the prototype of the newly constructed object and uses the function itself as the constructor.

Therefore, the object constructed from the new operation of the same function is considered to be an instance of a class. The common characteristics of these objects are: 1. have the same Prototype 2. it is processed by the same constructor. Instanceof is an operator that checks whether an instance belongs to a class in combination with this implementation class. You can also guess whether an object has been processed by a constructor, but it is much easier to check its prototype. Therefore, the implementation of instanceof can be understood from the prototype perspective, check whether the [[prototype] attribute of an object is consistent with the prototype of a specific function. Note that [[prototype] is a private attribute. In SpiderMonkey (the JS engine of Firefox), it can be accessed using _ proto.

The prototype only makes sense for the Object type described in the standard. Therefore, instanceof gets false for all non-Object objects, and instanceof can only determine whether it belongs to a certain type and cannot obtain a type, however, the advantages of instanceof are obvious. It can distinguish the objects constructed by custom "classes.

Instanceof can actually be spoofed. Although the object's private attribute [[prototype] cannot be changed, the prototype of the function is a common attribute. The following code shows how to cheat instanceof:

Function ClassA () {}; function ClassB () {}; var o = new ClassA (); // construct A Class A Object ClassB. prototype = ClassA. prototype; // ClassB. prototype replaced by alert (o instanceof ClassB) // true spoofing successful --!

Object. prototype. toString -- is a good method? Object. prototype. toString is hard to be called. All the built-in JavaScript classes overwrite the toString method, and the Object is not constructed by the built-in class. prototype. toString can only obtain meaningless [object Object] results. So for a long period of time, the Magic effects of this function have not been discovered.

In the standard, Object. prototype. toString has only three descriptions.

  1. Obtain the [[class] attribute of this object
  2. Concatenate the three strings "[object", Result (1), and "]" to calculate a string.
  3. Returned results (2)

Obviously, Object. prototype. toString is actually just getting the [[class] attribute of the Object, but I don't know if it's intended. All JS built-in function objects: String Number Array RegExp ...... [[Class] attributes are all set for new object construction, so that the [[class] attribute can be used as a good basis for determining the type.

Because Object. prototype. toString is the property of this Object, so you only need to use Object. prototype. toString. call or Object. prototype. toString. apply: You can specify this object and obtain the type.

Object. prototype. although toString is clever, it cannot obtain the User-Defined Function to construct the object type, because the user-defined function does not set [class], in addition, this private property cannot be accessed in the program. The biggest advantage of Object. prototype. toString is that it can make 1 and new Number (1) the same type of Object. In most cases, they are used in the same way.

However, it is worth noting that the result of new Boolean (false) is the opposite to that of false when involved in the bool operation. If the two are regarded as the same type at this time, it is easy to cause errors that are hard to be checked.

Summary

In order to compare the above three types of judgment methods, I made a table so that you can have a comprehensive comparison between several methods. To facilitate the comparison, I unified the results obtained by several judgment methods:

Object Typeof Instanceof Object. prototype. toString Standard
"Abc" String -- String String
New String ("abc ") Object String String Object
Function hello (){} Function Function Function Object
123 Number -- Number Number
New Number (123) Object Number Number Object
New Array (1, 2, 3) Object Array Array Object
New MyType () Object MyType Object Object
Null Object -- Object Null
Undefined Undefined -- Object Undefined

In fact, it is hard to say which of the above methods is more reasonable. Even the Standard Rules only reflect the runtime mechanism of JS rather than the best use practices. My personal opinion is to dilute the concept of "type", and pay more attention to the constraint "how to use this object, use typeof with instanceof to check whether the same effect can be achieved with strong types of languages as needed.

Appendix 1 IEEE 754 double-precision floating-point representation (from Chinese wikipedia ):

Sign bit: Used to indicate positive and negative numbers.

Exponent (exponential): used to represent the power

Mantissa (mantissa): Used to indicate Accuracy

Related Article

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.