You don't even have JavaScript (1)--types, values, and variables

Source: Internet
Author: User
Tags arithmetic operators variable scope

Text is contained in szhshp.org/tech/2017/02/18/javasprite.html

Reprint Please specify

Type, value, and variable wrapper object and original value

There are 5 primitive types of ECMAScript (primitive type)

    1. Undefined
    2. Null
    3. Boolean
    4. Number
    5. String

    • The base type (null, undefined, bool, number, string) should be a value type, with no properties and methods .

Built-in objects

JavaScript has a set of built-in objects to create basic language functions, such as the following

Boolean

A Boolean object represents two values: true or false . When called as a constructor (with operator new), Boolean () converts its arguments to a Boolean value and returns a Boolean object that contains the value. If called as a function (without the operator new), Boolean () will only convert its arguments to an original Boolean value, and return this value, if the value parameter is omitted, or set to,,,, 0 -0 null "" false undefinedor NaN , the object is set to False. Otherwise, set to true even if the value parameter is a string false .

BooleanObjects include toString and valueOf methods, which are Boolean most commonly used in simple judgments of true or false values in conditional statements, a combination of Boolean values and conditional statements provides a way to create logic using Javascript.

Number

The number object is a numeric wrapper that contains several read-only properties:

    • max_value: Maximum number of 1.7976931348623157e+308//javascript capable of processing
    • min_value: Minimum number of 5e-324//javascript capable of processing
    • negative_infinity:-infiny//Negative infinity
    • positive_infinity: INFINITY//Positive Infinity
    • nan: Nan//non-numeric

NumberObjects also have methods that you can use to format or convert values:

    • toexponential //string representation of numbers returned in exponential form
    • toFixed //rounding numbers to a number that specifies the number of decimal digits
    • toprecision //Converts an object's value beyond a specified number of digits to an exponential count method
    • toString //Returns a string representation of a number
    • valueOf //Inherit from Object
String

StringThe object is the wrapper for the text value. In addition to storing text, String an object contains a property and various methods to manipulate or gather information about the text, and the String object does not need to be instantiated to be able to use it.

StringObject has only one read-only length property to return the length of the string. The string object has many methods:

    • CharAt
    • charCodeAt
    • Concat
    • fromCharCode
    • IndexOf
    • LastIndexOf
    • Match
    • Replace
    • Search
    • Slice
    • Split
    • Substr
    • Substring
    • toLowerCase
    • toUpperCase
Wrapping Object

In addition to the above three objects, JavaScript also has a date, Array, math and other built-in objects, these three are often shown to use, so very familiar with the built-in objects can see the above example is what the case.

As long as it is a property and method that references a string, JavaScript converts the string value through new string (s) to the built-in object string, which is destroyed once the reference is finished. So the above code is actually using the length property of the string object and the IndexOf method.

Similarly, the processing of numbers and Booleans is similar. Null and undefined have no corresponding object.

Since there is object generation, can this be:

var s= ' This is a string '; s.len=10;  Creates a temporary string object that immediately destroys alert (S.len);  The third line of code creates a new temporary object and does not return 10, but undefined! A = 1;A.S = 2;a.s//as undefined
    • The second line of code simply creates a temporary string object, which is then destroyed.
    • The third line of code creates a new temporary object, naturally without the Len attribute.
    • This created temporary object becomes the wrapper object .
How to differentiate between original objects and wrapper objects

JavaScript converts the wrapped object to its original value when necessary so that the created object and its corresponding original values are often, but not always, displayed. The operator treats the == original value as equal to its wrapper object, but the === congruent operator treats them as unequal, and the typeof operator can see the difference between the original value and the wrapper object.

Immutable primitive values and mutable object references

Primitive values ( undefined ,, null boolean values, numbers, and strings) in JavaScript are fundamentally different from objects, including arrays and functions. The original value cannot be changed: No method can change (or 突变 ) a raw value. This is obviously true for numbers and booleans-changing the value of a number itself makes no sense, and is less obvious to a string, because the string looks like an array of characters, and we expect that the characters in the string can be modified by specifying the index. In fact, JavaScript is forbidden to do so. All methods in the string appear to return a modified string, in effect returning a new string value.

The original value of the string cannot be modified by var str = "abc"; str[0] = "D"; Console.log (str[1]= "F"); >>fconsole.log (Str[0]); >>aconsole.log (str); >>abc

The comparison of the original value is a comparison of values, but the object is a reference type and therefore can be considered an address comparison

var a = {' X ': 1}, B = {' X ': 1};alert (A = = B);//false, same value but different address var c = [1], d = [1];alert (c = = = d);//false, ibid.
object is converted to the original value
    • Object to Boolean is simpler, all objects to Boolean are true, including wrapper class new Boolean (False) is an object instead of the original value, it is converted to true
    • objects to numbers , objects to strings are more complex. Note that the local object is discussed here and does not contain the host object (for example, browser-defined objects)

All of the objects inherit the following two conversion methods:

ToString ()

Its function is to return a string that reflects the object. The default ToString () method does not return an interesting value.

Many classes define a specific version of the ToString () method:

    • the ToString () of the array
      Method converts each array element to a string and adds a comma between the elements to combine them into a result string
    • ToString () of the function class
      method returns the representation of the implementation definition for this function. Typically, a user-defined function is converted to a JavaScript source code string
    • Date Class ToString ()
      Returns a readable date and time string.
    • ToString () of the RegExp class
      Converts the returned RegExp object to a direct amount string that represents a regular expression.
[1,2,3].tostring ()//=> ' A-n ' (function (x) {f (x);}). ToString ()//=> ' function (x) {\nf (x); \ n} '/\d+/g.tostring ()//=> '/\\d+/g ' Newdate (2010,0,1). toString ()//=> ' Fri Jan 00:00:00 GMT-0800 (PST) '
ValueOf ()

Objects are composite values, and most objects cannot really represent a primitive value. arrays, functions, and regular expressions simply inherit this default method, and the valueof () method that invokes instances of these types simply returns the object itself. The valueof method of the date class returns an internal representation: the number of milliseconds since January 1, 1970

In general, objects can be converted to strings and objects to numbers by using the ToString () and valueof () methods.

Object-to-string conversion logic
    1. If you have the ToString () method, call this method if it returns a primitive value, JS converts it to a string, and returns the result of this character.
    2. If there is no ToString () or the method does not return a primitive value, then JS will call ValueOf (). If there is a call to it, if the return value is the original value. It is converted to a string.
    3. If no ToString () or valueof () gets a raw value, a type error exception is thrown.

Logic is clear, first try to toString() get the correct value, if not to try again valueOf() , otherwise error.

Object-to-numeric conversions
    1. If the object has the valueof () method, which returns a primitive value, JavaScript converts the original value to a number and returns the number
    2. Otherwise, if the object has the ToString () method, which returns a primitive value, JS converts the original value back to
    3. Otherwise, the JS report type is wrong.

The above is the original translation, may be some difficult to read, but in fact, it is easy to understand: first try valueOf() and then try again toString() , otherwise error.

Numeric conversions when using the operator
    The + operator inside
    • JavaScript can be used for addition or string join operations. If one of the operands is an object, then the object is converted to the original value instead of the object-to-number conversion. The

    • = = operator is similar, and if the object is compared to an original value, that object is also converted to an original value. In addition, date types are a special case, and dates are the only predefined types in the JavaScript language core. for all non-date objects, the conversion of the object to the original value is essentially an object-to-number conversion (first call valueof ()), and the Date object uses the object-to-string conversion pattern. and the original value returned by valueof () or ToString () is used locally and is not cast to a number or string.

    • and = = , < operators and other relational arithmetic operators will also do the object to the original worthwhile conversion, but If it is a Date object, a special logical is used for the bold characters above. Therefore, any object comparison other than the Date object will first attempt to call valueof and then call ToString. Regardless of whether the resulting raw value is used directly, it is not further converted to a number or string.

    • + , = = , ! = The relational operator is the only operator that performs a special string-to-original value conversion. The conversion of other operators to a particular type is clear, and there is no special case for date objects. For example, the - operator converts its two operands to a number. The following shows the result of the various operations of the Date object:

var now=new date  (); Console.log (typeof (Now+1));//string + number convert date to string//for the plus operator, we convert the operand to a string and then perform the calculation console.log ( typeof (Now-1)); Number-The conversion of the object to a number//for the minus operator, we will convert the operand to a number and then calculate Console.log (Now==now.tostring ()); True//For comparison operators, we typically convert to original values and then compare//But date type exceptions! Comparisons with date objects are converted to strings and then compared Console.log (now>now-1);//true > Convert dates to Numbers
Variable declaration
    • The initial value before the variable is not assigned is, no, no undefined null , no null null !
    • We do not declare types to variables, so it is also legal to reassign a variable that is already a number to a string, but it is generally not possible to avoid this.
Duplicate declarations and omissions of statements
    • Declaring the same variable multiple times with the Var statement is not only legal, but it does not cause any errors.
    • If a duplicate declaration has an initial value, then it assumes the role of an assignment statement.
    • If you try to read the value of an undeclared variable, JavaScript generates an error.
    • If you attempt to assign a value to a variable that is not declared with Var, javascript implicitly declares the variable.
    • Note, however, that implicitly declared variables are always created as global variables, even if the variable is used in only one function body. Local variables are used only in one function, and to prevent the creation of global variables (or the adoption of existing global variables) when local variables are created, you must use the VAR statement inside the body of the function. whether it is a global variable or a local variable, it is best to create it using the VAR statement.
Variable scope
    • All variables that are directly assigned to the definition are automatically declared as having global scope
    • In general, window the built-in properties of an object have global scope, such as, window.name window.location ,, and window.top so on.
    • Although you can write code at the global scope without writing var statements, you must use statements when declaring local variables var .
Scope = "global";           Declare a global variable without even declaring the function checkscope2 () {    scope = "local" in Var)        ; Bad! We have just modified the global variable    myscope = "local";      This explicitly declares a new global variable    return [scope, myscope];//returns two values of}console.log (Checkscope2 ()); ["Local", "local"], resulting in side effects console.log (scope);         "Local", global variable Modified console.log (myscope);       "Local", the global namespace messed up
    • function definitions can be nested.
var scope = "global scope";         Global variable function checkscope () {    var scope = "local scope";      Local variable     function nested () {        var scope = "nested scope";//local variable within nested scope        return scope;               Returns the value in the current scope    }    return nested ();} Console.log (Checkscope ());          "Nested Scope"
function scope and declaration in advance

In some C-like programming languages, each piece of code within the curly braces has its own scope, and the variables are not visible outside of the code snippet that declares them, and we call it block scope, which does not have block-level scopes in Javascript. Javascript uses the function scope instead, and variables are defined in the body of the function that declares them, and in any function within which the function body is nested.

In the code shown below, variables are defined in different locations, i j and k They are all within the same scope, and these three variables are defined within the body of the function.

function Test (o) {    var i = 0;//I have a defined    if (typeof o = = "Object") in the entire function body {        var j = 0;//j is defined in the body of the function, not just in this generation  Within the code segment        for (var k = 0; k < k++) {//k is defined in the function body, not just within the loop            Console.log (k);//Output Digital 0~9        }        console.log (k); K already defined, output ten    }    Console.log (j);//J already defined, but may not initialize}

the function scope of Javascript is that all variables declared within a function are always visible inside the function body. Interestingly, this means that the variable is even available before the declaration. This feature of JavaScript is informally called Declaration advance (hoisting), that is, all the variables declared in the JavaScript function (but not the assignment) are "ahead" to the top of the function body, and look at the following code:

var scope = "global"; function f () {    console.log (scope);  Output "undefined" instead of "global"    //because in this scope the local variable already overrides the global variable, but has not yet executed to    var scope = "local";//The variable assigns the initial value here, But the variable itself is defined in the function body anywhere in the    console.log (scope);  Output "local"}

You might mistakenly assume that the first row in the function is output "global" because the code has not yet executed to the point var where the statement declares the local variable. In fact, because of the function scope, local variables are always defined throughout the function body, that is, local variables in the function body obscure global variables of the same name. However, local variables are truly assigned only when the program executes to var the statement. Therefore, the above procedure is equivalent to: Declare the variable inside the function "ahead" to the top of the function body, while the variable initialization remains in its original position:

function f () {  var scope;//The local variable Console.log (scope) is declared at the top of the function;//the variable exists, but its value is "undefined" scope = "local";//Initialize it here and assign a value of C Onsole.log (scope); Here it has the value we expect}

In a block-scoped programming language, it is a very good programming practice to have variable declarations and code that uses variables as close to each other in a narrow scope as possible . Since Javascript does not have block-level scopes, some programmers deliberately place variable declarations at the top of the function body, rather than placing declarations near the use of variables. This approach makes their source code very clearly reflect the real variable scope.

A variable as a property

When you declare a JavaScript global variable, you are actually defining a property of the global object.

when declaring a variable with VAR, the property created is not configurable, meaning that the variable cannot be deleted by the delete operator. you may have noticed that JavaScript automatically creates a global variable if you do not use strict mode and assign a value to an undeclared variable. Variables that are created in this manner are normal properties of the global object and can be deleted:

var a =1;b =2;this.b2 = 3;delete A;    Delete B cannot be deleted;    Delete deleted this.b2  //Can be deleted

The JavaScript global variable is a property of the global object, which is known in the ECMAScript 5 specification as the declaration context object. JavaScript allows you to reference global objects with the This keyword, but there is no way to refer to objects stored in local variables. The unique nature of the object that holds the local variable is an internal implementation that is invisible to us. However, the idea that these local variable objects exist is very important.

You don't even have JavaScript (1)--types, values, and variables

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.