JavaScript is introduced
What is JavaScript?
Javascript is an object-oriented, cross-platform scripting language.
What are the features of JavaScript?
- Interpreted scripting languages
- Run in a browser (browser kernel with JS interpreter, Chrome V8 engine)
- Weakly typed language (loose type)
- Event-driven (dynamic)
- cross-platform
What is JavaScript used for?
- Embed dynamic text in HTML pages
- Responds to browser events
- Reading and writing HTML elements
- Validate data before it is submitted to the server
- Detect the visitor’s browser information (you can use JS code to determine the browser type)
- Control cookies, including creation and modification
- Server-side programming based on Node.js technology
JavaScript scope?
Scope: Scope of a variable, including:
- The global variable
Scope is the execution scope of the entire program. Variables defined outside the function body are global variables, and variables defined inside the function body without var are also global variables.
- A local variable
The scope is inside a function body. Variables or parameters defined by the var keyword inside the function body are local variables. When local variables have the same name as global variables, local variables take precedence over global variables inside the function body.
- Variable ascension
Variable declarations are promoted to the top of the current scope, but assignment is not promoted
Temporary dead zones
Redeclaring the same variable in the same function or block scope raises a SyntaxError;
Using it before declaring a variable or constant raises a ReferenceError. This is the temporary dead zone.
There are two main potholes:
- Switch Case Scope of the case statement in the case
switch (x) {
caseZero: let foo;
break;
case 1: let foo; // TypeError for redeclaration. break; } Copy the code
The error is reported because there is only one block-level scope in the switch.
let x = 1;
switch(x) {
case 0: {
let foo;
break; } case 1: { let foo; break; } } Copy the code
- A temporary dead area associated with lexical scope
function test() { var foo = 33;
if (true) {
let foo = (foo + 55); // ReferenceError
} } test(a);Copy the code
Foo is declared in the if statement with let, so foo in (foo+55) is referenced in the if block-level scope, not in the test function; But because foo in if hasn’t been declared yet.
In this line, the “foo” of the if block has been created in the lexical environment, but has not yet reached (and terminated) its initialization (which is part of the statement itself)
So it remains in the temporary dead zone
Variable life cycle
The life of a global variable does not end until the browser unloads the page. Local variables exist only during the execution of the function, where they are allocated space on the stack or heap to store their values, and then used in the function until the end of the function
Execution environment execution stack
Execution environment Execution stack (also known as execution context – Execution Context).
When the JavaScript interpreter initializes the execution code, it first enters the global execution environment by default. From this point on, each call to the function creates a new execution environment, and each execution environment creates a new environment object and pushes it onto the stack.
When the execution stream enters a function, the function’s environment objects are pushed into an execution stack. After the function completes execution, the stack ejects its environment, returning control to the previous execution environment.
Strict mode
In addition to normal mode, ECMAscript 5 adds a second mode: “Strict Mode”. As the name suggests, this mode makes Javascript run under more stringent conditions. Its main purposes are as follows:
- Eliminate some unreasonable and inaccurate Javascript syntax, reduce some weird behavior;
- Eliminate some unsafe code operation, to ensure the safety of code operation;
- Improve the efficiency of the compiler, increase the running speed;
- Set the stage for future versions of Javascript.
“Strict mode” represents a more sensible, secure, and rigorous approach to Javascript, and is now supported by major browsers, including IE 10.
The same code that works in non-strict mode may not work in strict mode.
How do I get into strict mode
<script>
"use strict"
console.log("Has entered strict mode.");
</script>
Copy the code
Strict mode behavior changes
- Global variables must be declared with var
<script>
"use strict"
a = 10; // Error because a is not declared by var //Uncaught ReferenceError: a is not defined; Error: A is not declared </script> Copy the code
- This cannot point to a global object
<script>
"use strict"
// console.log("Has entered strict mode.");
function a() {this.b = 10; // Error because this refers to the window object; //Uncaught TypeError: Cannot set property 'b'of undefined; Type error: cannot set attribute B for undefined; } Window. (a);</script> Copy the code
- Identical attributes within a function
<script>
"use strict";
functionA, b, b, c) {/ / an errorconsole.log(b,b,c); // in normal mode 2,2,3
// Uncaught SyntaxError: Duplicate parameter name not allowed inthis context ; Syntax error: Duplicate parameter names are not allowed in this context } A (1, 2, 3)</script> Copy the code
- The arguments object
Arguments objects are not allowed to change dynamically;
<script>
function fn1(a) {
a = 2;
return [a, arguments[0]];
}
console.log(fn1(1)); // normal mode is [2,2] function fn2(a) { "use strict"; a = 2; return [a, arguments[0]]; } console.log(fn2(1)); // strict mode is [2,1]</script> Copy the code
Arguments objects are not allowed to be self-called
<script>
"use strict";
var f = function() { return arguments.callee; };
f(); / / an error
//Uncaught TypeError: 'caller'.'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them // Type error:"caller", "arguments.callee", cannot be used in strict mode; //callerReturns a reference to the function calling the current function (property of the executing function)// Callee returns a reference to the function itself being executed (arguments' attribute) </script> Copy the code
this
This is the js keyword, which dynamically points to the currently invoked object according to the execution context (execution environment); Who calls, refers to who;
Call (), apply(), and bind() can redirect this
Js object
Everything in JS is an Object: numbers, strings, arrays, Math, Object, functions
The essence of an object in JS: a collection of properties and methods (unordered, so the object has no length attribute).
To explain objects in more official language:
What is an object is a type, a reference type. The value of the object is an instance of the reference type. In ECMAScript, a reference type is a data structure that organizes data and functionality together. It’s also often called a class, but ECMAScript6 didn’t have one before. Although ECMAScript is an object-oriented language, it does not have the basic structures, such as classes, that traditional object-oriented languages support.
The characteristics of
Encapsulation, inheritance, polymorphism
- Packaging:
1. Write objects
2. Use objects
Put some related objects and properties together and use a variable to abstract them off. This completes the encapsulation of the object
- Inheritance:
‘
Child objects can use some of the parent object’s properties and methods
- Polymorphism:
Overwrite, override
Overloading is based on different parameter types, parameter number to achieve different functions
Overrides are methods of the parent class that don’t work well, so I redefine a different method with the same name
Define the way
- literal
var obj = {
Key/value pair key:value
}
Copy the code
- New operator
var obj = new Object()
Copy the code
- The constructor
function Person(name,age,job){
this.name= name;
this.age = age;
this.job = job;
this.sayName = function() { alert(this.name); } } var person1 = new Person('monkey', 30,'web'); var person2 = new Person('zhu', 25,'h5'); Copy the code
- The factory pattern
The factory pattern abstracts the process of creating concrete objects. Since classes cannot be created in ECMAScript, developers have invented a function that encapsulates the details of creating objects with a particular interface, as in the following example:
function createPerson(name,age,job){
var o = new Object();
o.name = name;
o.age = age;
o.job = job;
o.sayName = function() { alert(this.name); } return o; } var person1 = createPerson('monkey', 30,'web'); var person2 = createPerson('zhu', 25,'h5'); Copy the code
- ES6 class grammar sugar
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() { return '(' + this.x + ', ' + this.y + ') '; } } Copy the code
Commonly used method
Built-in objects
String
There are two ways to create strings (constants and constructors). Common apis include:
- CharAt () returns the character at the specified position
- IndexOf () retrieves strings, returning subscripts
- LastIndexOf () searches strings from back to front.
- CharCodeAt () returns the Unicode encoding of the character at the specified position.
- FromCharCode () creates a string from the character encoding.
- Concat () Connection string.
- Match () finds one or more matches.
- Replace () replaces the substring that matches the regular expression.
- Search () retrieves the value that matches the regular expression.
- Slice () extracts a fragment of a string and returns the extracted portion in a new string.
- Split () splits a string into an array of strings.
- Substr () extracts the number of characters in the string from the starting index number.
- Substring () extracts the character between two specified index numbers in a string.
- ToLowerCase () converts the string toLowerCase.
- ToUpperCase () converts the string toUpperCase.
- Trim () Removes Spaces before and after strings (ES5)
- StartsWith () whether the string startsWith a character (ES6)
- EndsWith () whether the string endsWith a character (ES6)
- Whether the includes() string contains a certain character (ES6)
- Repeat () Several times over a string (ES6)
Math
Common attributes of Math are:
- Math.e returns the arithmetic constant E, the base of the natural logarithm (approximately equal to 2.718).
- Math.ln2 returns the natural logarithm of 2 (approximately 0.693).
- Math.ln10 returns the natural log of 10 (approximately equal to 2.302).
- Math.log2e returns logarithm base 2 of e (approximately equal to 1.414).
- Math.log10e returns logarithm base 10 of e (approximately equal to 0.434).
- Math.pi returns PI (approximately equal to 3.14159).
- Math.sqrt1_2 returns returns the reciprocal of the square root of 2 (approximately equal to 0.707).
- Sqrt1_2. SQRT2 returns the square root of 2 (approximately equal to 1.414).
Common apis include:
- Abs (x) returns the absolute value of the number.
- Sine of x returns the sine of a number.
- Cosine of x returns the cosine of the number.
- Tangent of x returns the tangent of the Angle.
- Ceil (x) logarithms are rounded up.
- Floor (x) logarithms are rounded down.
- Round (x) Rounds the number to the nearest whole number.
- Max (x,y) returns the highest value of x and y.
- Min (x,y) returns the lowest value of x and y.
- Pow (x,y) returns x to the y power.
- SQRT (x) returns the arithmetic square root of the number.
- Random () returns a random decimal number between 0 and 1, including 0 and no 1
Date
Common apis include:
- GetDate () returns the day of the month (1-31) from the Date object.
- GetDay () returns a day of the week (0 to 6) from the Date object.
- GetMonth () returns the month (0 to 11) from the Date object.
- GetFullYear () returns the year as four digits from the Date object.
- GetYear () use getFullYear() instead.
- GetHours () returns the hour of the Date object (0 to 23).
- GetMinutes () returns the minutes of the Date object (0 to 59).
- GetSeconds () returns the number of seconds (0 to 59) of the Date object.
- GetMilliseconds () returns the milliseconds (0 to 999) of the Date object.
- GetTime () returns the number of milliseconds since January 1, 1970.
- GetTimezoneOffset () returns the minute difference between the local time and Greenwich Mean Time (GMT).
- Parse () returns the number of milliseconds from midnight on January 1, 1970 to the specified date (string).
- SetDate () sets the Date of the month (1 to 31) in the Date object.
- SetMonth () Sets the month (0 to 11) in the Date object.
- SetFullYear () sets the year (four digits) in the Date object.
- SetYear () use setFullYear() instead.
- SetHours () sets the hours (0 to 23) in the Date object.
- SetMinutes () sets the minutes (0 to 59) in the Date object.
- SetSeconds () sets the number of seconds (0-59) in the Date object.
- SetMilliseconds () sets milliseconds (0 to 999) in the Date object.
- SetTime () sets the Date object in milliseconds.
Js array
At school, the class is divided into groups, as shown in the picture below, a vertical row is a group
A column is an array, an array there are many elements (multiple students), because JS is weakly typed language, so the array is also weakly typed, the same array variable can have various types of elements.
Define the way
- literal
var arr = [];
Copy the code
- New operator
var arr = new Array();
// constructor methodvar arr = new Array(10); // A parameter index length is 10Var arr = new Array(10,20,30); // Multiple arguments define array elementsCopy the code
Commonly used method
- Concat () : Joins two or more arrays and returns the result.
- Join () : Puts all the elements of an array into a single string. Elements are separated by the specified delimiter.
- Pop () : Removes and returns the last element of the array
- Push () : Adds one or more elements to the end of the array and returns the new length.
- Shift () : Removes and returns the first element of the array
- Unshift () : Adds one or more elements to the beginning of the array and returns the new length
- Reverse () : Reverses the order of elements in an array
- Slice () : Returns the selected element from an existing array
- Sort () : Sorts the elements of an array
- Splice () : Deletes elements and adds new elements to the array
- ToString () : Converts an array to a string and returns the result
ES5 New array method
- indexOf()
Checks if an element exists in the array, returns -1 if it does not, and returns its first occurrence if it does
- lastIndexOf()
The lastIndexOf() method returns the last occurrence of a specified string value, searching backwards in a specified position within a string
- forEach()
This function iterates through each element of the array. It takes three parameters: item, index, and array
- map()
The new array is a mapping of the original array. The original array is not changed. The elements of the new array are the values returned each time the function returns
- filter()
Filter elements and return a new array consisting of the elements that the function returns true each time; The original array is not affected
- some()
If one of the items returned by return is true, the final value will be true. The array will not be iterated through. If none of the items is true, the array will be returned false.
- every()
The result is true only if the function returns true for each item in the array. As long as either item returns false, the result is false. And none of the following elements continue to execute the function; The original array is not affected
- reduce()
The reduce() method takes a function as an accumulator, and each value in the array (from left to right) starts to shrink and eventually evaluates to a value. Reduce () can be used as a higher-order function for compose of functions
Reduce () does not perform callbacks on empty arrays
- reduceRight()
The function of the reduceRight() method is the same as that of reduce(), except that reduceRight() adds the items in the array forward from the end of the array.
ReduceRight () does not perform callbacks for empty arrays
ES6 New array method
- find()
Pass in a callback function that finds the first element in the array that matches the current search rule, returns it, and terminates the search
- findIndex()
We pass in a callback function that finds the first element in the array that matches the current search rule, returns its subscript, and terminates the search
- fill()
To replace an element in an array with a new element, you can specify the range of substitution subscripts.
Format: arr.fill(value, start, end)
- copyWithin()
Select an index of the array and copy the array elements from there, starting at 0 by default. You can also specify a range of elements to copy.
Format: arr.copywithin (start position to be replaced, start position to select the replacement value, end position to select the replacement value)
- Array.from()
Convert array-like objects and iterable objects into true arrays
- Array.of()
Used to convert a set of values into an array
- entries()
Return iterator: Returns key-value pairs
- values()
Returns the value of the key-value pair
- keys()()
Returns the key of the key-value pair
- Includes ()
To determine whether the element is present in the array, use parameters such as the value searched and the starting position to replace the ES5 era indexOf. IndexOf determines whether an element is a NaN, which is incorrect.
ES6 new
let/const
Block-level scope: a scope that is ubiquitous in all languages;
Extended operators…
The three dots function to expand an array or array-like object into a series of comma-separated values
var foo = function(a, b, c) {
console.log(a);
console.log(b);
console.log(c);
}
var arr = [1, 2, 3]; // The traditional wayfoo(arr[0], arr[1], arr[2]); // Use the extension operatorfoo(... arr);/ / 1/ / 2/ / 3Copy the code
Rest operator.
The REST operator is also three dots, but does the exact opposite of the extension operator, combining comma-separated sequences of values into an array
// Mainly for indeterminate arguments, so ES6 can stop using arguments objects at firstvar bar = function(a, ... args) { console.log(a);
console.log(args);
}
bar(1, 2, 3, 4); / / 1//[2, 3, 4]Copy the code
Template string
There is a new string in ES6 that is enclosed in (the character on the tilde > the backquote); Usually we want to concatenate a string with a label in this way:
bianliang + " This is a text" + obj.name + "</strong> " + bianliang
Copy the code
But with ES6 strings everything is much simpler;
` ${bianliang}<strong> This is a text${obj.name}</strong>${bianliang} `
Copy the code
Expanding variables with ${} makes concatenation very easy;
=> arrow function
The old way of writing it
var test = function(x){
return x+2;
}
Copy the code
Using the arrow function:
var test = x =>x+2;
Var function name = parameter => operation rule;
Copy the code
The arrow function this points to immobilization, not because the arrow function has a mechanism to bind this, but because the arrow function does not have its own this, so the inner this is the outer code block’s this. Because of this, arrow functions cannot be constructors either. There are two major drawbacks:
- Arrow functions cannot be new; they are not designed as constructors
- Var test = ()=>({id:3, val=20}) var test = ({id:3, val=20})
Deconstruction assignment
Var [a, b, c] = [1, 2, 3].var {a,b,c} = {
a:1,
b:2,
c:3
} var username = "zhangsan"; var age = 18; var obj = {username,age}; Copy the code
Set and Map structures
Think at the beginning of the design of JS, due to the participation of SUN company personnel and then the heyday of JAVA and its excellent design, just make JS syntax and memory design with JAVA will be so close. But there are a lot of great things in JAVA that JS hasn’t introduced for whatever purpose, such as sets and maps
The Set collection
A Set is essentially a wrapper around an array. For example:
let imgs = new Set();
Imgs. Add (1);Imgs. Add (1);Imgs. Add (5);imgs.add("5");imgs.add(new String("abc")); imgs.add(new String("abc")); // Print the result: 1 5'5' 'abc' 'abc' Copy the code
The Set is repeated by default, but only if the two added elements are exactly equal, so 5 and “5” are not equal, and the two new strings are not equal
Since a Set is essentially a map, there are several strange traversal methods
var imgs = new Set(['a'.'b'.'c']);
// traversal by KEYfor(let item of imgs.keys()){
console.log(item);
} //a //b //c Copy the code
// iterate according to VALUEfor(let item of imgs.values()){
console.log(item);
} //a //b //c
Copy the code
// traversal according to key-valuefor(let item of imgs.entries()){
console.log(item);
} / / /'a'.'a'] //['b'.'b'] //['c'.'c']
Copy the code
/ / normal for... Of cycle (for... Of withforThe difference between the -in is obvious, that is, the value of the -in is directly evaluated.for(let item of imgs){
console.log(item);
} //a //b //c
Copy the code
The SET collection does not provide subscript access, so it can only be traversed using for.
// Here is an ingenious way of removing the weight of an array
var newarr = [...new Set(array)];
Map collections
A set of maps
let map = new Map();
map.set("S230"."Zhang");
map.set("S231"."Bill");
map.set("S232"."Fifty");
Get an element, map.get("s232"); / / CathyCopy the code
// Loop over with destruct assignment
for(let [key,value] of map){
console.log(key,value);
}
Copy the code
BOM
The structure of BOM (Browser Object Model) is as follows:
Window is the global browser built-in top-level object that represents the window open in the browser (there is no public standard for window objects, though all browsers support them).
In client-side JavaScript, the Window object is a global object, and all expressions are evaluated in the current environment.
That is, no special syntax is required to refer to the current window, and properties of that window can be used as global variables.
For example, you can just write document instead of window.document.
Similarly, you can use the methods of the current Window object as functions, such as alert() instead of window.alert ().
In addition to the properties and methods listed above, the Window object implements all of the global properties and methods defined by the core JavaScript.
The global variable
Global variables are hung under window by default, for example:
var a = 123;
alert(window.a)//123
Copy the code
A child object under window
location:
- Window.location. href The URL of the current page, which can be retrieved or modified (page jump).
- Window.location. hostname Specifies the domain name of the Web host
- Window.location. pathName Specifies the path and file name of the current page
- Window.location. port Port of the Web host (80 or 443)
- Window.location. protocol Web protocol used (http:// or https://)
- Window.location. search Request parameter (? What follows)
- Window.location.reload () refreshes the page.
Normally, pass a true to reload() and let it refresh without caching. The cache is usually JS files, CSS files, etc. Using this method, you can make your own page move. Refresh the current page.
window.navigator:
- Navigator.appname returns the name of the current browser.
- Navigator. AppVersion Returns to get the version number of the current browser.
- Navigator. platform returns the operating system of the current computer.
These attributes have been gradually abandoned.
A new attribute replaces these attributes.
Navigator. userAgent returns browser information (use this property to determine the current browser)
Example to determine the current browser type:
function isBrowser() {
var userAgent = navigator.userAgent;
// wechat built-in browser if(userAgent.match(/MicroMessenger/i) == 'MicroMessenger') {
return "MicroMessenger";
} //QQ built-in browser else if(userAgent.match(/QQ/i) == 'QQ') { return "QQ"; } //Chrome else if(userAgent.match(/Chrome/i) == 'Chrome') { return "Chrome"; } //Opera else if(userAgent.match(/Opera/i) == 'Opera') { return "Opera"; } //Firefox else if(userAgent.match(/Firefox/i) == 'Firefox') { return "Firefox"; } //Safari else if(userAgent.match(/Safari/i) == 'Safari') { return "Safari"; } //IE else if(!!!!! window.ActiveXObject ||"ActiveXObject" in window) { return "IE"; } else { return "Undefined :"+userAgent; } } Copy the code
history:
- The history.go(1) argument can be written to any integer, with positive numbers forward and negative numbers backward
- History. The back () back
- History. The forward ()
Screen: the screen
- Window.screen. width Returns the current screen width (resolution value)
- Window.screen. height Returns the current screen height (resolution value)
Popbox method under window:
- Alert () Displays an alert box
- Prompt () brings up an input box
- Confirm () displays a confirmation box
DOM
DOM (Document Object Model), which defines the objects, behaviors, and properties needed to represent and modify a Document, as well as the relationships between these objects.
Get DOM node
- Document. The getElementById (id)
- getElementsByTagName
What you get is a set (not just one, but a bunch)
- GetElementsByName () gets the element from the Name value, and the return value is a collection, usually used to get the input value with Name
Not all tags have a name value, and older browsers may have compatibility issues
- GetElementsByClassName (class name)
Internet Explorer 8 cannot be used
- Document.queryselector () (ES5)>>>> Once an element is matched, no further matches are made
- Document. QuerySelectorAll () (ES5) > > > > strong to beyond imagination; All the elements that meet the requirements are matched. IE8+ is supported
Properties get and manipulate
- GetAttribute () gets the attribute value of the element
- SetAttribute () sets the attributes of the element
- RemoveAttribute () Deletes the attribute
History of good articles recommended:
After reading the salary increase is no longer a dream
2, the history of the strongest VUE summary ~ ten thousand words long – interview development depends on it
I know. What are macro tasks and micro tasks?
4, sharp code non weapon vscode
Interview guide takes you to the top of your life
I am Monkeysoft, your “three lines” is the biggest power of monkeysoft creation, if this article has any mistakes and suggestions, welcome to leave a comment!
The article continues to update, you can wechat search [little monkey’s Web growth path] pay attention to the public number for the first time to read, after paying attention to the background reply knowledge system, more can receive xiaobian carefully prepared front-end knowledge system, future learning is no longer confused, more can join the technology group exchange and discussion.
This article is formatted using MDNICE