JavaScript-basic types, reference types, basic packaging types, monolithic built-in objects

basic type

Basic data types: Number, String, Boolean, Null, undefined. Mixed data types: object
reference data types: Array, Date, RegExp, Function
type of data types: object, number, function, boolean, undefined

ECMAScript variables include values ​​of two different data types: basic type values ​​and reference type values.
Basic type value: simple data segment
Reference type value: refers to an object that may be composed of multiple values; a reference type value is an object stored in memory.
JavaScript does not allow direct access to locations in memory, that is, you cannot directly manipulate the memory space of objects. When manipulating objects, it is actually manipulating the reference of the object rather than the actual object.

Reference type

The value (object) of the reference type is an instance of the reference type.
Reference types are sometimes called object definitions because they describe the properties and methods of a class of objects.
New objects are created using the new operator followed by a constructor. The constructor itself is a function, except that the function is defined for the purpose of creating new objects. (Please see another article for Array type)

object type

Object type native reference type
Most reference type values ​​are instances of object type;
there are two ways to create an object instance:
1. Use the new operator followed by the Object constructor var person = new Object ();
2. Object literal representation law. It is a shorthand form of object definition that simplifies the process of creating objects that contain a large number of attributes.
var person = {"name": "ABC"};
When using object literal syntax, the attribute name can also use the string
var person = {"name": "ABC", "age": 29,5: true} ; 5 will also be automatically converted to a string

In general, dot notation is used when accessing object properties, and JavaScript can also use square bracket notation to access object properties. The advantage of the square bracket syntax is that attributes can be accessed through variables. It is recommended to use dot notation
var propertype = "name";
alert (person [propertype]); "ABC"

Date type

The Date type uses the number of milliseconds since midnight (zero hour) on January 1, 1970 UTC to save the date. The
Date.parse () method receives a string parameter representing a date, and then attempts to return the millisecond of the corresponding date based on this string
The behavior of the Date.parse () method varies by implementation, and usually varies by region.
United States: "month / day / year" "English month, day, year" "English day of the week English month day day hour: minute: Second time zone "
var someDate = new Date (Date.parse (" May 25,2004 "));
var someDate = new Date (" May 25,2004 "); Equivalent, the background automatically calls Date.parse ()
Date.now () Method, returns the number of milliseconds representing the date and time when this method was called.
example:

var start = Date.now();  //取得开始时间
dosomething(); //调用函数
var stop = Date.now();  //取得停止时间或 var stop = + new Date();
result = stop - start; 在不支持它的浏览器中,使用+操作符获取Date对象时间戳

RegExp type (local object)

  1. var expression = / pattern / flags; Regular expressions defined in the form of literals
    flags: indicate the behavior of the regular expression
    g: indicate global mode. That is, the pattern will be applied to all strings, instead of stopping immediately when the first match is found
    i: indicates a case-insensitive pattern
    m: indicates that the multi-line pattern
    is similar to the expression in other languages, the pattern used in All metacharacters must be escaped.
    Metacharacters in regular expressions: ([{\ ^ $ |)? * +.]}
  2. Use RegExp constructor with two parameters: string pattern to match, optional flag string
    var pattern = new RegExp ("\ [bc \ at", "i");
    The main method of RegExp object is exct () The
    second method designed specifically for capturing groups is test (), which takes a string parameter and returns true if the pattern matches the parameter.

Function type

The function is actually an object.
Since the function is an object, the function name is actually a pointer to the function object and will not be bound to a function

  1. Function declaration syntax

    function sum(num1,num2){
    return num1+num2;
    }

  2. Function expression definition function

    var sum = function(num1,num2){
    return num1 + num2;
    }

  3. Using the function constructor, you can receive any number of parameters, the last parameter is seen as the function body

    var sum = new Function (“num1”, “num2”, “return num1 + num2”); not recommended

Because the function name is just a pointer to the function, the function name is no different from other variables that contain object pointers.
A function will have several names

function sum(num1,num2){
	return num1+num2;
}
alert(sum(10,10));//20
var anotherSum = sum;
alert(anotherSum(10,10));//20
sum = null;
alert(anotherSum(10,10));//20

Declare the variable anotherSum and set it equal to sum (assign the value of sum to anotherSum), pay attention! The function name without parentheses is to access the function pointer, not to call the function. At this time, both otherSum and sumd point to the same function, sum is set to null, and does not affect anothersum.

No overloading
declare two functions with the same name, and the result is that the latter function overwrites the previous function

The difference between the original data type and the reference data type

The storage location is different
. The simple data segment where the original data type is directly stored in the stack has a small space and a fixed size. It belongs to frequently used data, so it is placed on the stack to store the
reference data type. The size is not fixed. If it is stored in the stack, it will affect the performance of the program. The reference data type stores the pointer in the stack, and the pointer is changed to point to the starting address of the entity in the heap. When the interpreter looks for the reference value, it will first retrieve the address in the stack, and get the entity from the heap after getting the address.

Defining the value of the basic type and the reference type are similar: creating a variable and assigning a value to the variable. When this value is saved in the variable, the operations that can be performed on different types of values ​​are very different. For values ​​of reference types, you can add attributes and methods to them, and you can also change and delete their attributes and methods.

Basic packaging type

In order to facilitate the operation of basic type values. ECMAScript provides three special reference types: Boolean, Number, and String
var s1 = "some text";
var s2 = s1.substring (2);
basic type values ​​are not objects, and logically they should not have methods.
When the second line of code accesses s1, the access process is in a reading mode, that is, the value of this string is to be read from it. When accessing a character string in read mode, the background will automatically complete the following processing. The basic string value becomes the same as the object.

1. Create an instance of type String
2. Call the specified method on the instance
3. Destroy this instance
var s1 = new String ("some text");
var s2 = s1.substring (2);
s1 = null;

Number type

The toString () method passes a parameter that expresses the cardinality and tells it to return the string form of the decimal value.
var num = 10;
alert (num.toString ()); // "10"
alert (num.toSting (2)); // "1010" binary
toFixed () returns a numeric string according to the specified decimal places represents
Alert (num.toFixed (2)); // "10.00"
var NUM = 10.005;
Alert (num.toFixed (2)); // "10.01" automatic rounding

String type

Each instance has a length attribute

Character method

Two methods for accessing specific characters in a string: charAt () and charCodeAt () The
charAt () method returns the character at a given position in the form of a single-character string
var stringvalue = "hello world";
alert (stringvalue. charAt (1)); // “e”
charCodeAt () gets the character encoding
alert (stringvalue.charCodeAt (1)); // “101”
can use square brackets plus a numeric index to access specific characters in the string
alert ( stringvalue [1]); // "e" IE7 previously returned undefined

String manipulation method

  1. The concat () method concatenates one or more strings, and returns the new string obtained by concatenation.
    var result = stringvalue.concat ("!"); Multiple parameters can be accepted without affecting the original string
    alert (result); / / "Hello world!"
    More string concatenation is plus operator (+)

  2. ECMAScript provides three methods for creating new strings based on substrings: slice (), substr (), and substring () all return a substring of the manipulated string, and all accept one or two parameters. Will modify the string itself

  • The first parameter specifies the starting position of the substring, the second parameter of the slice () and substring () specifies the position after the last string of the subcharacter, and the second parameter of the substr () specifies the return Number of characters
  • The parameter is a negative value. The
    slice () method adds the incoming negative value to the length of the string. The
    substr () method adds the negative first parameter to the length of the string, and converts the negative second parameter to 0, the
    substring () method will turn all negative parameters to 0
  1. String position method The method for
    finding a string from a string: indeOf () and lastIndexOf () return the position of the substring.
    Both can accept the optional second parameter, indicating from which position in the string to start the search

  2. tirm () method
    creates a copy of the string, deletes all spaces before and after the suffix, and then returns the result
    var str = "hello"; alert (str.trim ()); // "hello"

  3. String case conversion methods
    toLowerCase (), toLocaleLowerCase (), toUpperCase (), toLocaleUpperCase ()

  4. String pattern matching method

  • The essence of match () is the same as the exec () method of calling RegExp. It only accepts one parameter. The regular expression / RegExp object
    var text = "cat, bat, sat, fat";
    var pattern = /.at/; // and pattern. exec (text); same
    var matches = text.match (pattern);
    alert (matches.index); // 0
    alert (matches [0]); // “cat”
    alert (pattern.lastIndexOf ()); // "0"

  • The way to find the pattern is that search ()
    returns the index of the first match in the string
    var text = "cat, bat, sat, fat";
    var pos = text.search (/ at /);
    alert (pos); // The first occurrence of "at" in the string

  • replace () method
    Two parameters, RegExp object or a string, a string or a function
    var text = "cat, bat, sat, fat";
    var result = text.replace (/ at / g, "ond") ;
    alert (result); // "cond", "bond", "sond", "fond"


  • The separator specified by the split () method separates a string into multiple substrings and puts the result in an array. The separator can be a string or a RegExp object. Two parameters are optional Size
    var colorText = "red, blue, green, yellow";
    var color1 = colorText.split (","); // ["red", "blue", "green", "yellow"]
    var color2 = colorText. split (",", 2); // [[red "," blue "]

  1. localeCompare () method, compare two strings, according to the sorting rules in the alphabet

  2. The formCharCode () method receives one or more character codes and then converts them into a string. charCodeAt () performs the opposite operation

The main difference between reference types and basic packaging types is the lifetime of objects

Instances of reference types created using the new operator are kept in memory until the execution flow leaves the current scope. The automatically created objects of the basic packaging type exist only at the moment of execution of a line of code, and then are immediately destroyed. This means that we can no longer add properties and methods to basic type values ​​at runtime.
Calling typeof on an instance of a basic package type will return "object", and all objects of the basic package type will be converted to boolean true.

Monolithic built-in objects (gload, Math cannot be instantiated)

ECMAScript-262 definition: Objects provided by the EXMAScript implementation that do not depend on the host environment. These objects already existed before the execution of the ECMAScript program.
All properties and functions defined by Global and Math in the global scope are properties of the Global object

  1. URI encoding method
    The encodeURI () and encodeURIComponent () methods of the Global object can encode the URI (Universal Resource Identifier) ​​for sending to the browser

  2. eval () method The
    eval () method is like a complete ECMAScript parser, it only accepts one parameter, the ECMAScript (or JavaScript) string to be executed
    eval ("alert (" hi ")); equivalent to alert ( "Hi");
    the code executed by eval () can refer to the variable defined in the containing environment
    var msg = "hello world"; eval ("alert (msg)"); // "hello world"
    created in eval () Any variables or functions will not be promoted, because when parsing the code, they are included in a string, which is only created when eval () is executed

window object

ECMAScript does not indicate how to directly access the Global object, but Web browsers implement this global object as part of the window object. Therefore, in the global scope, all variables and functions declared become window objects Attributes.
Another way to get Global objects

var global = function(){
	return this;
}();

Execute the function immediately and return this value. If the value of this is not specified for the function, this value is equal to the Global object

Math object

  1. min () and max () methods
    To find the maximum or minimum value in an array, as follows:
    var val = [1,2,3,4,5,6,7,8];
    var max = Math.max.apply (Math , val);
    Take the Math object as the first parameter of apply to set this value correctly

  2. Rounding method
    Math.ceil () rounds up Math.ceil (25.9); // 26
    Math.floor () performs rounding down Math.floor (25.9); // 25
    Math.round () standard rounds 25.9 -> 26 25.5-> 26 25.1-> 25

  3. rondom () method
    returns a random number greater than or equal to 0 and less than 1
    value = Math.floor (Math.random () * may be worth the total + the first possible value)
    between 1 and 10 var num-Math.float (Math .random () * 10 + 1)

Copy variable value

If you copy a basic type value from one variable to another, a new value is created on the variable object, and then the value is copied to the location where the new variable is assigned.
When copying a reference type value from one variable to another, the value stored in the variable object is also copied to the new variable allocation space. The difference is that this worthwhile copy is a pointer, and this pointer points to an object stored in the heap. After the copy operation ends, the two variables actually refer to the same object, so changing one of the variables will affect the other.
example:

  1. var num1 = 5; var num2 = num1;
    The value stored in num1 is 5, when the value of Num1 is used to initialize num2, the value 5 is also saved in num2, but 5 in num2 and 5 in num1 are completely independent. The value is just a copy of 5 in num1. After that, the two variables can participate in any operation without affecting each other.
  2. var obj = new Object (); var obj2 = obj1; obj1.name = "ABC"; alert ( obj2.name ); // "ABC"
    obj1 holds a new instance of an object, this value is copied to obj2, obj1, obj2 refers to the same object. obj1 adds the name attribute, and obj2 can also access this attribute.

This article is from the summary of "JavaScript Advanced Programming"

Published 17 original articles · praised 0 · visits 769

Guess you like

Origin blog.csdn.net/CandiceYu/article/details/89888802