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).
- 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
- Consists of letters, numbers, underscores, or dollar signs.
- You can’t start with a number.
- 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:
- Var variable name = value
- 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.
learningnumber
knowledge
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.
learningisNaN
knowledge
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
Number()
parseInt()
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
String()
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
- What is an expression
- Classification of JavaScript operators
- 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
- Arithmetic operator
- Logical operator
- The assignment operator
- Comparison operator
- 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.
- The assignment operator
- Comparison operator
- 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
- 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
for
for-in
while
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
- role
- define
- 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.
Array
String
Math
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
push()
Add the parameter to the end of the array.unshift()
Add the parameter to the front of the array.pop()
Delete the last element and return the deleted element.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:
charAt()
charCodeAt()
indexOf()
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:
slice()
substring()
substr()
Array objects also have the syntax for slice()
For interception of strings:
Grammar: stringObject. Slice (start, end)
Function to intercept substrings.
Parameter Description:
start
Is the starting position of the specified string.end
To indicate where the string ends,end
It’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
min()
max()
ceil()
, rounded up.floor()
, and round down.round()
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
getFullYear()
Returns the 4-digit year.getMonth()
Returns the month in the date, with the value 0-11.getDate()
Returns the number of days in a month.getDay()
Returns week of the week with the value 0-6.getHours()
Return hour.getMinutes()
Return to the point.getSeconds()
Return to seconds.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
setFullYear(year)
Set to 4 digits.setMonth(mon)
Sets the month in the date.setDate()
Set the date.setHours()
Set hours.setMinutes()
Set points.setSeconds()
Set the seconds.setTime()
Setting a date in milliseconds changes the entire date.
Error handling
Chrome DevTools
Basic 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
- Syntax errors are impossible to run successfully.
- 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
getElementById()
getElementByName()
getElementByTagName()
getElementByClassName()
querySelector()
querySelectorAll()
How to get elements
document.getElementById()
- Gets the element by ID
- Return an element
- Case sensitive to ids (IE8 and above)
document.getElementsByClassName()
- Gets the element by class name
- The return is a pseudo-array
- Internet Explorer 8 or later is not supported
document.getElementsByTagName()
- Gets the element by tag name
- Returns a pseudo-array
- Compatibility is very good
document.getElementsByName()
- Gets by name, typically applied to forms
- Return pseudoarray
- This applies only to tags that are valid for the name attribute.
Pseudo array
- Must be an object
- Must have the length attribute
- Content must be stored in index + content
- 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
- Interline styles can be read and written
- Values written must be in string format
window.getComputeStyle(ele,null)
- Null places can hold pseudo classes
- You return absolute values
- It is read-only and cannot be modified
ele.currentStyle
- It is read-only and cannot be modified
- Returns the absolute value of the conversion
- Attributes unique to IE
ele.id ele.title
- Get style: ele.style.prop– inefficient and not easy to maintain
- Ele.classname — Easy to maintain
Gets the content of the element
innerHTML:
- On assignment: tags are parsed as tags and not printed on the page
- When extracting content: The label is extracted as well
innerText:
- On assignment: The tag is parsed into text and printed on the page
- 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
appendChild()
insertBefore()
replaceChild()
cloneNode()
normalize()
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
removeChild()
removeNode()
innerHTML
deleteContents()
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()
ie
Private implementation of- Delete the target node from the document and return to the target node
- The argument is a Boolean value. The default value is
false
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
getNamedItem()
removeNamedItem()
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:
onload
Triggered when the page loadsonclick
Triggered when the mouse clicksonmouseover
Trigger when the mouse slidesonmouseout
Triggered when the mouse leavesonfoucs
Triggered when you get focusonblur
Triggered when you lose focusonchange
Occurs 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:
- Only one can be bound to an element
this
Point to thedom
The element itself
2.obj.addEventListener(type,fn,false);
IE9
Following incompatibilities- Multiple events can be bound to an element
this
Point to thedom
The element itself
3.obj.attchEvent("on"+type,fn);
IE
unique- Multiple events can be bound to an element
this
Point to thewindow
onsubmit
Occurs when the confirm button in the form is clickedonmousedown
Fires when the mouse button is pressed on the elementonmousemove
Occurs when the mouse pointer movesonmouseup
Triggered when the mouse button is released on the elementonresize
Triggered when the browser window is resizedonscroll
Drag the scroll bar to scroll
Keyboard events andkeyCode
attribute
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/target
The event source is the element at which the event occurs.cancelBubble
Boolean property, set totrue
, will stop the event further bubbling to the elements of the containment level.returnValue
Boolean property, set tofalse
To 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:
- Variables inside a closure do not pollute the world because they are enclosed inside the closure
- All variables are kept private and private in closures
Afterword.
Scan the public account to subscribe for more exciting content.