Abstract

The sample code for JavaScript Advanced Programming can be found in the attachment.

Chapter 2 <script> elements

The defer attribute

Set defer=”defer” and the script will be delayed until the entire page has been parsed. Multiple deferred scripts will not necessarily be executed in sequence.

Async attributes

Set async=”async” to load script content asynchronously, but multiple asynchronous scripts may not be executed in sequence.

< noscript > element

This element can contain any HTML element (except script) that can appear in <body>, and the browser will only display the content in <noscript> if the browser does not support scripting or if scripting is supported, but scripting is disabled.

Chapter three Basic concepts

The typeof operator

Typeof is an operator that returns the data typeof that data. Note, however, that for primitive types, the correct result can be returned except for NULL (which returns Object and is considered an empty Object reference). For reference types, return object all but function(return function).

Boolean type

Use the Boolean() function to convert a value of any type to a Boolean value. The use of “!!!!! The first Boolean nonoperator converts the value to a Boolean value and inverts it. The second Boolean nonoperator inverts the value again to get the true Boolean value.

The Number type

JS stores the minimum value in number.min_value, which is 5e-324; Save the maximum value in number. MAX_VALUE, which is 1.7976931348623157e+308. If the value of a calculation exceeds this range, the value is automatically converted to a special Infinity value (Infinity is plus Infinity, -infinity is minus Infinity). Use isFinite() to determine whether a value isFinite.

NaN is not a number, and any operation involving NaN returns NaN and NaN is not equal to any value, including NaN itself. The isNaN() function takes an argument and can determine if it is “not a number.” NaN also applies to objects, first calling valueOf() of the object, then determining whether the return value can be converted to a value, and if not, testing the return value by calling toString() based on the return value.

Number(), parseInt(), and parseFloat() convert non-numeric values to numeric values:

  • Number() : Converts any data type to a numeric value. The null value is converted to 0; Undefined converts to NaN; The empty string is converted to 0.
  • ParseInt () : Converts a string to a value. An empty string is converted to NaN. Accepts the second argument to set the base of the conversion.
  • ParseFloat () : Converts a string to a numeric value, able to parse decimal.

Type String

There are two ways to convert a value to String.

  • ToString () : Each value has a toString() method, which returns a string representation of the value (null and undefined do not have this method). When you call toString() for a value, you can pass an argument that specifies the base of the output value.
  • With String(), returns toString() if the value has a toString() method, and null and undefined return null and undefined.

Unary addition operator

In addition to being used for basic arithmetic operations, the unary addition operator, when applied to a non-numeric value, performs a conversion on the value as the Number() transformation function does.

function

Since ECMAScript functions are not signed, their arguments are represented by arrays containing zero or more values, and true overloading is impossible without function signatures.

Chapter 4 variables, scopes, and Memory Problems

Variable value copy

  • If a value of the primitive type is copied from one variable to another, a new value is created on the variable object and then copied to the location allocated for the new variable, and the two variables can participate in any operation without affecting each other.
  • When a variable copies the value of a reference type to another variable, the value of the pointer is copied to the space allocated by the new variable, because the variable stores the pointer to the object. Therefore, after the copy ends, the two variables will actually reference the same object, and changing one variable will affect the other variable.

Parameter passing

Copying a value from outside a function to an argument inside a function is just like copying a value from one variable to another. Primitive type value passing is the same as primitive type variable copy, and reference type value passing is the same as reference type variable copy.

Execution environment and scope

Each execution environment has a variable object associated with it that defines all variables and functions in the environment. When code is executed in an environment, a scope chain of variable objects is created. The purpose of scope chains is to ensure orderly access to all variables and functions that the execution environment has access to. The scope chain is always preceded by the variable object of the environment in which the code is currently executing. If the environment is a function, the active object is used as a variable object. Active objects start out with only arguments objects.

Variable declarations

Variables declared using VAR are automatically added to the nearest environment. If a variable is initialized without a var declaration, it is automatically added to the global variable.

The garbage collection

Values that leave scope are automatically marked as recyclable and will be deleted during garbage collection. “Tag sweep” is the current mainstream garbage collection algorithm, marking values that are not currently in use and then reclaiming their memory. “Reference counting” keeps track of how many times all values are referenced, but is no longer used because the “reference counting” algorithm can cause problems when there are circular references.

Chapter 5 Types of citation

The Object type

There are two ways to create an Object instance. One is to use the new operator followed by the Object constructor. The other is to use object literals. When an Object is defined through an Object literal, the Object constructor is not actually called.

Array type

There are two basic ways to create arrays:

  • The first is to use the Array constructor, which allows you to pass parameters to the constructor. If the value is passed, an Array of the specified number of items will be created. If it is any other type of parameter, an Array containing the parameters will be created. You can omit the new operator when using the Array constructor.
  • The second is to use Array literals, which, like objects, do not call the Array constructor.

The length property of an array is not only read-only; you can set this property to remove items from the end of the array or add new items to the array.

Sort an array by calling toString() on each item and comparing the resulting strings, even if the items are numeric; The sort() method can take as an argument a comparison function that takes two arguments, returning a negative number if the first argument should come before the second, and so on.

The Date type

Using the new operator and the Date constructor, you can create a Date object based on the current Date and time. Use date.parse () and date.utc ()

  • Date.parse() takes a string argument representing a Date and returns the number of milliseconds for the Date. Date.parse() is also called in the background if you pass a string representing a Date directly to the Date constructor.
  • Date.utc () accepts year, zero-based month (January is 0), day of the month (1-31), hour (0-23), minute, second, and millisecond. Year and month are mandatory, and others default to minimum values. Passing the argument directly to the Date constructor creates the time based on the local time zone.
// The two are equivalent
var now = new Date("May 25, 2004");
var someDate = new Date(Date.parse("May 25, 2004"));

// 00:00 GMT on January 1, 2000
var gmtTime = new Date(Date.UTC(2000.0));
// 17:55:55 GMT, May 5, 2005
var gmtTime2 = new Date(Date.UTC(2005.4.5.17.55.55));

// 00:00 local time on 1 January 2000
var localTime = new Date(2000.0);
// 17:55:55 local time, 5 May 2005
var localTime2 = new Date(2005.4.5.17.55.55);
Copy the code

Date overrides toString() and toLocalString(), and returns a Date millisecond representation for valueOf().

The RegExp type

Regular expression syntax

var expression = / pattern/ flag
Copy the code

The pattern part can be any simple or complex regular expression. Each regular expression can have one or more flags. The matching mode of the regular expression supports the following three flags:

  • G: represents the global pattern, that is, the pattern is applied to all strings instead of stopping immediately when the first match is found;
  • I: Indicates a case-insensitive mode that insensitive mode and string case are ignored when determining a match.
  • M: Indicates multiline mode, that is, when the end of a line of text is reached, the search continues to see if there is an item matching the pattern in the next line.

For exec() of the RegExp instance, if the global flag (g) is not set, multiple calls to exec() on the same string will always return information about the first match; If the global flag (g) is set, each call to exec() continues to look for a new match in the string.

Each instance of a Regexp has the following properties through which various information about the schema can be obtained.

  • Global: A Boolean value indicating whether the G flag is set.
  • Ignorecase: Boolean value indicating whether the I flag is set.
  • Lastindex: integer representing the character position at which the search for the next match begins, counting from 0.
  • Multiline: Boolean value indicating whether the M flag is set.
  • Source: String representation of the regular expression, returned as a literal rather than as a string pattern in the passed constructor.

The RegExp constructor contains properties that apply to all regular expressions in scope.

  • Input Indicates the string to be matched last time
  • LastMatch indicates the lastMatch
  • LastParen last matched capture
  • The text before lastMatch in the leftContext Input string
  • Multiline Boolean indicating whether all expressions use multiline mode
  • RightContext Input The text after lastMatch in the string
  var text = "this has been a short summer"; var pattern = /(.) hort/g; /* * Note: Opera doesn't support input, lastMatch, lastParen, or multiline. * Internet Explorer doesn't support multiline.
   */        
  if (pattern.test(text)){
      alert(RegExp.input);               //this has been a short summer
      alert(RegExp.leftContext);         //this has been a            
      alert(RegExp.rightContext);        // summer
      alert(RegExp.lastMatch);           //short
      alert(RegExp.lastParen);           //s
      alert(RegExp.multiline);           //false
  }
Copy the code

The Function type

The difference between a function declaration and a function expression: the parser reads the function declaration first and makes it available before any code is executed; Functional expressions, on the other hand, cannot be interpreted until the parser reaches its line of code.

Alert (sum(10,10)); The function declaration was added to the execution environment before the code was executedfunction sum(num1, num2){
   returnnum1 + num2; } // alert(sum(10,10)); // Causes an error is not executed to the function expression, and sum does not contain a reference to the function. var sum =function(num1, num2){
   return num1 + num2;
}; 
Copy the code

Since functions in JS are objects, they also have properties and methods. Each function contains two properties, length and Prototype.

  • Length: The length attribute indicates the number of named arguments that the function wants to accept.
  • Prototype: For reference types, Prototype holds the actual location of all their instance methods. In other words, methods such as toString() and valueOf() are actually stored under prototypr names and are only accessed through instances of their respective objects.

Each function contains the apply() and call() methods, whose purpose is to call the function in a particular scope, essentially setting the value of this in the function body.

  • Apply () takes two arguments, the first is the scope in which the function is run and the second is an array of arguments, which can be arrays or arguments objects.
  • Call () does the same thing as apply, except that it accepts arguments differently. The first argument is the scope in which the function is run, and the rest of the arguments must be passed to the function one by one.
  • Bind () creates an instance of a function in which the this value is bound to the value passed to bind()
// apply() demo
function sum(num1, num2){
   return num1 + num2;
}
function callSum1(num1, num2){
   return sum.apply(this, arguments);
}
function callSum2(num1, num2){
   returnsum.apply(this, [num1, num2]); } alert (callSum1 (10, 10)); / / 20 alert (callSum2 (10, 10)); //20 // call() demofunction sum(num1, num2){
   return num1 + num2;
}
function callSum(num1, num2){
   returnsum.call(this, num1, num2); } alert (callSum (10, 10)); / / / / 20bind() demo
window.color = "red";
var o = { color: "blue" };                    
function sayColor(){
   alert(this.color);
}
var objectSayColor = sayColor.bind(o);
objectSayColor();   //blue
Copy the code

The real power of apply(), call(), and bind() is the ability to expand the scope of a function.

window.color = 'red';
var o = {color:'bluw'};

function sayColor() {
	alert(this.color);
}

sayColor();			// red

sayColor.call(this);	// red
sayColor.call(window);	// red
sayColor.call(o);		// blue
Copy the code

The biggest advantage of using call() or Apple () or bind() to extend the scope is that the object does not need to have any coupling to the method. Normally we need to put the sayColor() function into the object O and call it from o. With the call() function, we don’t need to do this. There is no coupling between the object and the method.