Hello, everyone, I am Nezha, not to say more, today is a "long summary of JavaScript, consolidate the front-end foundation" article, welcome to enjoy.Copy the code

preface

What is a JavaScript

JavaScript is an object – and event-driven client-side scripting language originally developed to verify the correctness of HTML form input, derived from Netscape’s LiveScript language.

Understand the history of JavaScript

liveScript ==> javaScript => ECMAscript

The relationship is as follows: liveScript is a generic name for javaScript. ECMAscript: defines a syntax specification for javaScript that describes the basic syntax and data types of the language.

Understand what JavaScript is made of

JavaScript is made up of the ECMAScript language, Browser Objects(DOM,BOM).

  1. Grammar:

Learn js annotations and semicolons

// Single-line comments

/**/ multi-line comments

A semicolon is used at the end of a statement, or if omitted, the end of the statement is determined by the following.

Learn JavaScript syntax

Everything in ECMAScript is case sensitive: variables, function names, operators.

Learning identifiers

What is an identifier, a variable, a function, the name of an attribute, or an argument to a function?

Naming rules for identifiers

  1. Consists of letters, numbers, underscores, or dollar signs.
  2. You can’t start with a number.
  3. Do not use keywords, reserved words, and so on as identifiers.

What are variables

What are variables? ECMAScript variables are loosely typed. Loosely typed means that any type of data can be stored.

Each variable is just a placeholder to hold the value.

Learn how to declare and assign variables

Declaration of variables: Declaration of variables using the var operator, syntax: var variable name.

Variable assignment:

  1. Var variable name = value
  2. Declare first and assign later, variable name = value

Declare multiple variables at once, separated by commas.

Note that variables declared by omitting var are global variables, and omitting the var operator is not recommended.

Understand JavaScript data types

ECMAScript divides simple data types and complex data types.

Simple data types are also known as basic data types, and notice the addition of the Symbol data type in ES6.

There are five basic data types:

undefined, null, boolean, number, string

Complex data types include object

Learn the Typeof operator

Typeof is the type used to detect variables.

Syntax structure, typeof variables or typeof

The return value is a string type, or a number, Boolean, object, function, undefined and so on.

Learning Undefined

Undefined has only one value, which is the special undefined.

Note: In general, there is no need to explicitly set a variable to undefined.

Learning to null

A null value represents an empty object pointer; If you define a variable to be used to hold objects in the future, it is best to initialize the variable to NULL rather than another value.

Undefined is derived from null, so undefined==null returns true.

learningnumberknowledge

Number: indicates integer and floating point numbers.

NaN is (not a number) is a special numeric value that is not a number.

Any operation that involves a NaN returns a NaN.

NaN is not equal to any value, including NaN itself.

learningisNaNknowledge

IsNaN (n) : checks whether n is non-numeric. The result is Boolean.

Description :isNaN() attempts to convert a received value to a value and then checks if it is not a value.

Numerical transformation

  1. Number()
  2. parseInt()
  3. parseFloat()

Number() can be used for any data type, and parseInt() and parseFloat() are used to convert strings into numbers.

ParseInt () ignores the space before the string until the first non-space character is found.

ParseInt () converts an empty string to return NaN.

ParseInt () this function provides the second argument, the cardinality to use when converting.

ParseFloat () parses each character starting with the first character until an invalid floating-point character is encountered.

Besides the first decimal point being valid, the second difference between parseFloat() and parseInt() is that it always ignores leading zeros.

Learning Striing

The String type is used to represent sequences of zero or more 16-bit Unicode characters.

Learn string conversion

  1. String()
  2. toString()

Str.tostring () converts STR to a string. Using the String() function, you can convert any type of value to a String.

Learning Boolean

A type used to indicate true and false, that is, true for true and false for false.

Learning type conversion

All numbers except 0 are true when converted to Boolean.

All characters other than “” are converted to Boolean to true.

Null and undefined are converted to Boolean false.

Arithmetic operator

  1. What is an expression
  2. Classification of JavaScript operators
  3. Learn arithmetic operators

An expression is a meaningful formula that connects data of the same type with operation symbols according to certain rules.

Classification of operators

  1. Arithmetic operator
  2. Logical operator
  3. The assignment operator
  4. Comparison operator
  5. Ternary operator

increasing

Both ++a and a++ increment a.

The difference between:

++a returns the incremented value of a, a++ returns the original value of a, and then returns the incremented value.

Same thing with decreasing.

  1. The assignment operator
  2. Comparison operator
  3. Ternary operator

Ternary operator

Grammar: Conditions? Execute code 1: Execute code 2

Logical operator

Logic and&&

Returns the first operand if the first operand is implicitly cast to true.

If the first operand is implicitly cast to false, the second operand is returned.

If only one of the operands is null NaN undefined, one of them will return null NaN undefined.

Logic or logic not

| | or, as long as there is one condition, return true

! No, logical no returns a Boolean value regardless of the data type of the operand.

Flow control statement

  1. Learn if, prompt(), alert()

Alert (), a warning dialog box is displayed

If statement

if(condition){
    statement1;
}else{
    statement2;
}
Copy the code

Grammar: prompt ()

The input box pops up with ok and cancel.

Var age = prompt(" Please enter your age ")Copy the code

NaN is not equal to anything, including itself

Document.wirte (), week access method, master switch

Syntax: new Date().getday ()

Return number(0-6)

var week = new Date().getDay();
console.log(week);
Copy the code

Multiple conditions can use the switch statement

Grammar:

switch(expression) { case value: statement break; case value: statement break; . defalut: statement }Copy the code

Output content to browser: document.write(” content “)

Loop statements in JavaScript

  1. for
  2. for-in
  3. while
  4. do... while

Grammar:

While (condition){execute code; }Copy the code

Grammar:

Do {code to execute}while(condition)Copy the code

The loop must be executed at least once.

Break statement and continue statement

Break Immediately exits the loop

Continue Completes the current loop and continues the next loop

Functions in JavaScript

  1. role
  2. define
  3. call

The function encapsulates any number of statements that can be called anywhere and executed at any time.

How functions are defined, using function declarations.

Function names belong to identifiers.

<script> // declare a function function myFun(){alert(" I am a function "); } // call myFun(); </script>Copy the code

The return value of the function

Declare a function with arguments:

function add(num1,num2){ var sum = sum1+sum2; return sum; } the console. The log (add (2, 3));Copy the code

The function stops and exits immediately after the execution of the return statement. The return statement may also have no return value. This is used when the function is stopped prematurely and no return value is required.

To master the arguments

Arguments in ECMAScript are represented internally as an array, which is accessed inside the function body via the arguments object.

Built-in objects

Objects: strings, functions, arrays

Built-in objects are objects wrapped by the browser itself.

  1. Array
  2. String
  3. Math
  4. Date

An array is used to store a set of data, how to create an array, how to read and write the elements of the array, the length property of the array.

Create an Array: Use the Array constructor, new Array(), using the literal notation.

Array stack method

  1. push()Add the parameter to the end of the array.
  2. unshift()Add the parameter to the front of the array.
  3. pop()Delete the last element and return the deleted element.
  4. shift()Delete the first element and return the deleted element.

Join (separator) : arrayObject.join(separator) : puts all the elements in an array into a string and returns the string.

Reverse () method, syntax: arrayObject.reverse(), used to reverse the order of elements in an array and return an array.

The sort() method, syntax: arrayObject.sort(sortby), is used to sort the elements of an array and returns an array. – By string.

Code:

arr.sort(function(a,b){return b-a});
Copy the code

The concat() method is used to concatenate two or more arrays and returns an array.

arr3 = arr1.concat(arr2);
Copy the code

Slice () returns the selected element from an existing array.

Grammar: arrayObject. Slice (start, end)

splice()Method – delete – Insert – Replace

Delete, syntax: arrayObject.splice(index,count), function: delete zero or more elements starting at index. The return value is an array of deleted elements.

If count is 0, no value is deleted. If count is not set, all values starting with index are deleted.

Arrayobject.splice (index,0,item1,… Itemx) for inserting a value at a specified position.

Arrayobject.splice (index,count, itemQ,… Itemx), inserts values in the specified position and deletes any number of items at the same time.

Index is the starting position, count is the number of items to delete, item1… Itemx is the item to insert.

Position -indexOf and lastIndexOf

IndexOf (), syntax, ArrayObject.indexof (searchValue,startIndex), function, looking backwards from the beginning of the array (position 0).

The return value is number, or -1 if not found, in the array.

LastIndexOf (), syntax: arrayObject.lastIndexof (searchValue,startIndex), function from the end of the array to find forward.

String String methods:

  1. charAt()
  2. charCodeAt()
  3. indexOf()
  4. lastIndexOf()

Difference between charAt() and charCodeAt()

Syntax: stringobject. charAt(index), function to return stringObject index position character.

Syntax: stringobject. charCodeAt(index), function to return stringObject in the index position character of the character encoding.

Interception of a string

Interception of string objects:

  1. slice()
  2. substring()
  3. substr()

Array objects also have the syntax for slice()

For interception of strings:

Grammar: stringObject. Slice (start, end)

Function to intercept substrings.

Parameter Description:

  1. startIs the starting position of the specified string.
  2. endTo indicate where the string ends,endIt’s not part of the interception.

substring()

The substring() syntax, the main difference being that this automatically converts to 0 when the argument is negative.

Substring () takes a small number as the start and a large number as the end.

Substr (), syntax: stringobject. substr(start, len)

The function is to intercept a string.

Start indicates the start of the string, len indicates the total number of characters to be truncated, and the end of the string is truncated when omitted.

When start is negative, the negative value passed in is added to the length of the string. If len is negative, the string is returned.

Code:

The value contains 11 characters

STR. The substring (6, 9); STR. Substr (6, 3); STR. Substr (5, 4); / / (6, 4) STR. Substr (3, 4);Copy the code

Get the extension

var url="http://xxx/index.txt";
function getFileFormat(url) {
    var pos = url.lastIndexOf(".");
    return url.substr(pos); // .txt
}
var formatName = getFileFormat(url);
Copy the code

split()

Syntax: stringobject. split(separator).

Function to split a string into an array of strings. The return value is array.

Separator is the separator.

replace()replace

Grammar: stringObject. Replace (regexp/substr, replacement)

Function: Replace some characters in a string with other characters, or replace a substring that matches a regular expression. The return value is String.

ToUpperCase () and toLowerCase ()

Syntax: stringobject.touppercase (), converts the string toUpperCase.

Syntax: stringobject.tolowercase (), converts string toLowerCase.

str.charAt(6).toUpperCase();
Copy the code

Convert the first letter of each word to uppercase, joining the rest of the characters

var newStr = word.charAt(0).toUpperCase()+word.substr(1);
Copy the code

Mathematical objects

  1. min()
  2. max()
  3. ceil(), rounded up.
  4. floor(), and round down.
  5. round()
  6. abs()

Round, ceil(), floor()

Math.ceil() syntax: math.ceil (num), which returns the smallest integer greater than num.

Math.floor(num), rounded down, returns the integer part of num.

Math.round() syntax that rounds values to the nearest whole number.

The absolute valueMath.abs()

Math.abs(num) returns the absolute value of num.

random()Method – random number

Encapsulates a function for finding random integers between n and m.

random=Math.floor(Math.random()*(m-n+1)+n);

Math.random() syntax, which returns random numbers greater than or equal to 0 and less than 1.

The date object

New Date() creates a Date and time object. Returns the current date and time object without taking a parameter.

Some common methods

  1. getFullYear()Returns the 4-digit year.
  2. getMonth()Returns the month in the date, with the value 0-11.
  3. getDate()Returns the number of days in a month.
  4. getDay()Returns week of the week with the value 0-6.
  5. getHours()Return hour.
  6. getMinutes()Return to the point.
  7. getSeconds()Return to seconds.
  8. getTime()Returns the number of milliseconds representing the date.

Code:

var today = new Date(),
year = today.getFullYear(),
month = today.getMonth()+1,
date = today.getDate(),
week = today.getDay(), // 0-6
hours = today.getHours(),
minutes = today.getMinutes(),
seconds = today.getSeconds(),
Copy the code

Set the method

  1. setFullYear(year)Set to 4 digits.
  2. setMonth(mon)Sets the month in the date.
  3. setDate()Set the date.
  4. setHours()Set hours.
  5. setMinutes()Set points.
  6. setSeconds()Set the seconds.
  7. setTime()Setting a date in milliseconds changes the entire date.

Error handling

  1. Chrome DevToolsBasic use of

Syntax error: error that does not conform to JS syntax.

Runtime error. Code has no syntax errors, but an error occurs at runtime.

How do you distinguish syntax errors from runtime errors

  1. Syntax errors are impossible to run successfully.
  2. It is possible for a runtime error to run successfully.

Logical error

What is a logical error? It means that the calculation is not as expected.

Code:

function foo() { try { throw new Error(); }catch(e){ return 1; }finally{ return 2; }}Copy the code

DOM node operation

DOM operations, add nodes, delete nodes, modify nodes, find nodes.

DOM document object model

Create a node

Document.write () creates the node

Create create method:

document.createElement()

document.createTextNode()

document.createDocumentFragment()

document.createComment()

The code create creates a node:

myReady(function(){
    var ul = document.getElementById("myList");
    var li = document.createElement("li");
    ul.appendChild(li);
});

<ul id="myList"></ul>
Copy the code

An efficient way to create a node:

The innerText outerText,

innerHTML,outerHTML

Node traversal

The documentElement property returns the root node of the document

The tagName attribute returns the tagName of the element

Class array object NodeList

HTMLCollection is an array object

  • Ele.getElementsByTagName()
  • document.scripts
  • document.links
  • document.images
  • document.forms
  • tr.cells
  • select.options

Example:

myReady(function(){
    var scripts = document.scripts;
    var links = document.links;
    var cells = document.getElementById("tr").cells;
    var imgs = document.images;
    var forms = document.forms;
    var options = document.getElementById("select").options;
    var ps = document.getElementsByTagName("p");
}
Copy the code

Class array object NamedNodeMap

  • Ele.attributes

Class array object dynamics

The three collections NodeList, HTMLCollection and NamedNodeMap are all dynamic.

Nodes to find

  1. getElementById()
  2. getElementByName()
  3. getElementByTagName()
  4. getElementByClassName()
  5. querySelector()
  6. querySelectorAll()

How to get elements

  • document.getElementById()
  1. Gets the element by ID
  2. Return an element
  3. Case sensitive to ids (IE8 and above)
  • document.getElementsByClassName()
  1. Gets the element by class name
  2. The return is a pseudo-array
  3. Internet Explorer 8 or later is not supported
  • document.getElementsByTagName()
  1. Gets the element by tag name
  2. Returns a pseudo-array
  3. Compatibility is very good
  • document.getElementsByName()
  1. Gets by name, typically applied to forms
  2. Return pseudoarray
  3. This applies only to tags that are valid for the name attribute.

Pseudo array

  1. Must be an object
  2. Must have the length attribute
  3. Content must be stored in index + content
  4. There are some basic features of arrays, but you can’t use array methods.

Get element attributes

El.setattribute (" Attribute Name "," attribute Value ") el.getAttribute (" Attribute name ") el.removeAttribute (" attribute name ") el.dataset. Prop =" value"Copy the code

dom.style.prop

  1. Interline styles can be read and written
  2. Values written must be in string format

window.getComputeStyle(ele,null)

  1. Null places can hold pseudo classes
  2. You return absolute values
  3. It is read-only and cannot be modified

ele.currentStyle

  1. It is read-only and cannot be modified
  2. Returns the absolute value of the conversion
  3. Attributes unique to IE

ele.id ele.title

  1. Get style: ele.style.prop– inefficient and not easy to maintain
  2. Ele.classname — Easy to maintain

Gets the content of the element

innerHTML:

  1. On assignment: tags are parsed as tags and not printed on the page
  2. When extracting content: The label is extracted as well

innerText:

  1. On assignment: The tag is parsed into text and printed on the page
  2. When extracting content: Tags are not extracted, only text content is extracted

value:

Use on forms

Offset series attributes

Scroll bar scrolling distance:

Below the window. PageYOffset (ie 9 does not support) document. The body. The scrollTop document. The documentElement. ScrollTop;Copy the code

Visual window size:

Window. The innerWidth (IE8 following incompatible) document. DocumentElement. ClientWidth document. The body. The clientWidth judgment weird model method (quirks mode) document.compatModeCopy the code

Scroll to the specified position

scroll(x,y)   scrollTo(x,y)  scrollBy(x,y);  
Copy the code

Nodes to findquerySelector()andquerySelectorAll()

QuerySelector () returns an element of the specified CSS selector

QuerySelectorAll () returns a list of elements for the specified CSS selector

Operation node

  1. appendChild()
  2. insertBefore()
  3. replaceChild()
  4. cloneNode()
  5. normalize()
  6. splitText()

AppendChild () adds a node after specifying the last child of the element node; this method returns the new child.

InsertBefore () inserts new child nodes before the specified existing child nodes.

ReplaceChild () this method is used to replace a child node with a new node. Returns the replaced node.

CloneNode () creates a copy of the node and returns that copy.

var myUrl = document.getElementById("myUrl"); var newNode = myUrl.cloneNode(true); // Depth, with child nodes, false by default, only parent nodesCopy the code

Normalize () can merge adjacent Text nodes.

Code:

myReady(function(){
    var div = document.createElement("div");
    var textNode = document.createTextNode("dom");
    div.appendChild(textNode);
    
    var textNode2 = document.createTextNode("web");
    div.appendChild(textNode2);
    document.body.appendChild(div);
    
    console.log(div.childNodes.length);
    div.normalize();
    console.log(div.childNode);
    console.log(div.firstChild.nodeValue);
}
Copy the code

SplitText () splits the text node into two nodes at the specified location.

Deleting a Node

  1. removeChild()
  2. removeNode()
  3. innerHTML
  4. deleteContents()
  5. textContent

RemoveChild () removes a specified child node from a node.

RemoveChild () must have parameters

myReady(function(){
    var myUrl = document.getElementById("myUrl");
    console.log(myUrl.childNodes.length);
    
    var secondChild = myUrl.removeChild(myUrl.childNode[1]);
    console.log(secondChild);
    console.log(myUrl.childNodes.length);
}
Copy the code

removeNode()

  1. iePrivate implementation of
  2. Delete the target node from the document and return to the target node
  3. The argument is a Boolean value. The default value isfalse

RemoveChild () compares with innerHTML

HTML DOM removeChild() method

var list=document.getElementById("myList");
list.removeChild(list.childNodes[0]);
Copy the code

Remove front:

Coffee
Tea
Milk
Copy the code

Removed:

Tea
Milk
Copy the code

Browser support Internet ExplorerFirefoxOperaGoogle ChromeSafari

All major browsers support the removeChild method

Syntax node. RemoveChild (node)

Create nodes, find nodes, manipulate nodes, delete nodes

DOM attributes

Example:

<div
id="div0"
class="active"
style=""
url=""
xxx=""></div>
Copy the code

Attributes include property and attribute

  1. getNamedItem()
  2. removeNamedItem()
  3. setNamedItem()

Example:

MyReady (function () {var inputs = document. QuerySelectorAll (" input "); inputs[0].checked = true; } <input type="checkbox">1 <input type="checkbox" checked="checked">2 <input type="checkbox" checked>3Copy the code

Gender: Male and female

Example:

Gender :<br/> <input type="radio" name="gender" value="male" checked> male <input type="radio" name="gender" value="female"> femaleCopy the code

Cities you’ve been to: Beijing and Shanghai

Example:

<br/> <select name="city" id="city"> <option value=" Beijing "> </option> <option value=" Shanghai ">Copy the code

Cities you’ve been to: Beijing, Shanghai, New York

Example:

Cities you have visited: <br/> <select name="city" id="city" multiple="multiple"> </option> <option value=" Shanghai" </option> <option value=" New York "> New York </option> </select>Copy the code

Common string properties

The front end

Example:

<p style="text-align:center" style=" margin: 0px; padding: 0px;Copy the code

The event

What is an event? Are moments of interaction that occur in a document or browser window.

Event method:

  1. onloadTriggered when the page loads
  2. onclickTriggered when the mouse clicks
  3. onmouseoverTrigger when the mouse slides
  4. onmouseoutTriggered when the mouse leaves
  5. onfoucsTriggered when you get focus
  6. onblurTriggered when you lose focus
  7. onchangeOccurs when the content of the domain changes

HTML event

Example:

<input type="button" value=" onclick='alert '" >Copy the code

The binding event

Methods for binding events:

1.onclick:

  1. Only one can be bound to an element
  2. thisPoint to thedomThe element itself

2.obj.addEventListener(type,fn,false);

  • IE9Following incompatibilities
  • Multiple events can be bound to an element
  • thisPoint to thedomThe element itself

3.obj.attchEvent("on"+type,fn);

  • IEunique
  • Multiple events can be bound to an element
  • thisPoint to thewindow
  1. onsubmitOccurs when the confirm button in the form is clicked
  2. onmousedownFires when the mouse button is pressed on the element
  3. onmousemoveOccurs when the mouse pointer moves
  4. onmouseupTriggered when the mouse button is released on the element
  5. onresizeTriggered when the browser window is resized
  6. onscrollDrag the scroll bar to scroll

Keyboard events andkeyCodeattribute

Onkeydown occurs when the user presses a keyboard key

Onkeypress occurs when a keyboard key is pressed

Onkeyup occurs when the keyboard key is released

KeyCode returns the character code of the value of the key, or the code of the key, triggered by the onKeyPress, onKeyDown, or onKeyUp events.

When a user interacts with a Web page in some way, the interpreter creates a response event object to describe the event information.

Event handle, called event handler, event listener function, refers to the function called in response to an event.

Untying of events

Remove the event, removeEventListener()

Grammar: element. The removeEventListener (event, function, useCapture), function, remove the addEventListener () method to add event handlers.

Example:

var btn2 = document.getElementById("btn2"); btn2.addEventListener('click',function(){ alert('btn2'); },false); Btn2. removeEventListener('click',function(){alert('btn2'); });Copy the code

The parameters in ADDXX and RemoVEXX are the same. Procedure

Ie Event Stream (IE Event Handler)

Add event: attachEvent()

Grammar: element. AttachEvent (event, function)

The function is used to add event handles to the specified element

Remove event

detachEvent()

Grammar: element. DetachEvent (event, function)

The function removes the event handle added by the attachEvent() method.

Event delegate and event bubbling

Event cycles: event capture (event objects propagate down the DOM tree), target firing (event listeners run), event bubbling (events propagate up the DOM tree).

Event bubbling and event capture

Example:

Document.getelementbyid ('parent').addeventListener ("click",function(e){alert("parent event triggered "+this.id); }) document.getelementById ("child").addeventListener ("click",ffunction(e){alert("child "+this.id); })Copy the code

The principle of event delegation is event bubbling

Event object properties and methods

Type Indicates the type of the event. SrcElement/Target Indicates the event source.

Blocking default behavior

var link = document.getElementById("mylink");
link.onClick = function(event){
    event.preventDefault();
}
Copy the code

Cancel event capture or bubbling

var btn = document.getElementById("myBtn");
btn.onclick=function(event){
    alert("Click");
    event.stopPropagation();
}
document.body.onclick = function(event){
    alert("Body clicked");
}
Copy the code

Target click on whoever is target, the source of the event

CurrentTarget points to whoever the event is bound to

ClientY is the position from the top and bottom of the browser to the mouse

PageY is the position from the top and bottom of the browser to the mouse

ScreenY is the top of the screen to the mouse position

Properties and methods in the Event object

  • srcElement/targetThe event source is the element at which the event occurs.
  • cancelBubbleBoolean property, set totrue, will stop the event further bubbling to the elements of the containment level.
  • returnValueBoolean property, set tofalseTo prevent the browser from executing the default event action.

Event objects are compatible across browsers

Example:

var EventUtil = { addHandler: function(element, type, handler) { }, getTarget: function(event){ return event.target || event.srcElement; }, preventDefault: function(event){ if(event.preventDefault){ event.preventDefault(); }else{ event.returnValue = false; }, removeHandler: function(element,type,handler){ }, stopPropagation: function(event){ if(event.stopPropagation){ event.stopPropagation(); }else{ event.cancelBubble = true; }}}}Copy the code

Event addEventListener attacEvent

Example:

var EventUtil = {
    addHandler: function(element,type,handler){
        
    },
    removeHandler: function(element,type,handler){
        
    }
}
Copy the code

What is the bom

Bom Browser object model.

The Window object

The Window object represents the Window open in the browser.

If the document contains frames ( or

The global variable

Window declaration and keyword declaration

Window. variable name = value and var variable name = value

Window object method

Grammar: window. Alert (” content “)

Grammar: window. Confirm (” message “)

Window Object properties
attribute describe
closed Returns whether the window is closed.
defaultStatus Sets or returns the default text in the window status bar.
document A read-only reference to the Document object
frames Returns all named frames in the window. This collection is an array of Window objects, each containing a frame within the Window.
history A read-only reference to the History object.
innerHeight Returns the height of the document display area of the window.
innerWidth Returns the width of the document display area of the window.
localStorage Store key/value pairs in the browser. There is no expiration date.
length Sets or returns the number of frames in a window.
location Location object for a window or frame. See the Location object.
name Sets or returns the name of the window.
navigator A read-only reference to a Navigator object

The timer

Timeout calls, intermittent calls

Grammar: setTimeout (code, millisec)

Grammar: setInterval (code, millisec)

Example:

var intervalId = setInterval(function(){ console.log("web"); }, 1000); setTimeout(function(){ clearInterval(intervalId); }, 10000);Copy the code

Functions can access variables defined internally by functions, such as:

The instance

function myFunction() {
    var a = 1;
    return a * a;
}
Copy the code

Functions can also access variables defined outside the function, such as:

The instance

var a = 1;
function myFunction() {
    return a * a;
}
Copy the code

Location object

The Location object provides information about the document loaded in the current window, as well as some navigation capabilities, and is an attribute of both the Window object and the Document object.

Location. href returns the full URL of the currently loaded page.

Location. host returns the server name and port number.

Location. hostname Returns the server name without the port number.

Location. pathname returns the directory and filename in the URL.

Location. port returns the port number specified in the URL, or an empty string if none is present.

Location. protocol Returns the protocol used by the page.

Location. search returns the query string for the URL.

To change the location of the browser:

The location. The href attribute.

Other properties of the Location object can also change the URL

The location. The hash and the location. The search

Location.replace () redirects the URL

Location.reload () reloads the currently displayed page

The history object holds a history of pages accessed by the user in the browser

History.back () returns to the previous step in the history

Example:

var btn = document.getElementById("btn"); Btn.onclick = function(){//history.back(); history.go(-1); }Copy the code

History.forward () The next step in the history

History. go(-n) returns to the first n steps of the history record

History.go (n) returns to the last n steps of the history record

Screen object properties

Screen.availwidth Returns the available screen width

Screen. availHeight Returns the available screen height

Get the height and width of the window document display area, using innerHeight and innerWidth

The navigator object

Example:

/ / test browser type function getBrowser () {/ / get the userAgent property var explorer = the navigator. UserAgent. ToLowerCase (), browser; if(explorer.indexOf("mise")>-1){ browser = "IE"; }else if(explorer.indexOf("chrome")>-1){ browser = "chrome"; }else if(explorer.indexOf("opera")>-1){ browser = "opera"; }else if(explorer.indexOf("safari")>-1){ browser = "safari" } return browser; }Copy the code

closure

What is the execution context?

console.log(a); / / undefined console. The log (this); //window b(); // b() is not a function c(); // "c" var a = "a"; var b = function () { var b = "b" console.log(b); } function c () { var c = "c" console.log(c); }Copy the code

A context stack is a stack that stores execution contexts, in which only one context is active. When executing global code, one global context is pushed onto the stack. When calling a function, a context of the function is generated and pushed onto the stack

Scope of JS – lexical scope

Js scope is lexical scope (static scope), in fact, most language scope is lexical scope, and lexical scope is the opposite of dynamic scope

What is a closure

Closures are functions that have access to variables in the scope of another function.

Use of closures

The variable object to which the scope chain points

The formation and pros and cons of closures

To form a closure is to pass a function as a value that also refers to the scope chain of another function so that the referenced function cannot be reclaimed

Advantages:

  1. Variables inside a closure do not pollute the world because they are enclosed inside the closure
  2. All variables are kept private and private in closures

Afterword.

Scan the public account to subscribe for more exciting content.