Your own summary of JavaScript basics

Source: Internet
Author: User

For an interview with a summary written by yourself, refer to the article: "JavaScript Advanced Programming"

1. Selector API
*queryselector ()
Queryselector () receives a CSS selector, returns the first element that matches the selector, and returns null if none.
When it is called with document, it is found in all document elements,
If this method is called with an element, it is found in all descendant elements of the element.
If the match to an illegal CSS selector, is an error.
*queryselectorall ()
Queryselector () receives a CSS selector, like Queryselectorall (), which returns a nodelist that satisfies the CSS selector,
Similarly, it can be called with document and element, and if no matching selector is found, an empty nodelist is returned, if
If the CSS selector is not valid, an error will be thrown.
*matchesselector ()
The Matchesselector () method receives a CSS selector that can return whether the calling element matches the selector, so
Its return value is a Boolean type and returns True if it can match, or false if it does not match.
Matchesselector () can generally be used to check if the selected element is returned by Queryselector () and Queryselectorall ().
But browsers are not very well supported matchesselector,ie9+ can support Msmatchesselector (),
firefox3.6+ can support Mozmatchesselector,chrome support for Webkitmatchesselector (), so you need to encapsulate a method yourself:

Function Matchesselector (element,selector) {
if (element.matchesselector) {
return element.matchesselector (selector);
}else if (element.msmatchesselector) {
return element.msmatchesselector (selector);
} else if (element.mozmatchesselector) {
return element.mozmatchesselector (selector);
} else if (element.webkitmatchesselector) {
return element.webkitmatchesselector (selector);
} else{
Throw new Error ("Browser not Supported");
}
}

2, Node properties in JavaScript
Node properties:
NodeType Each node has an integer that returns a value of 1~12, representing a different node type
ParentNode points to the parent node of each node, only one. The
ChildNodes returns all the child nodes of an element.
PreviousSibling Returns the previous sibling node of the current node, or null if the current node is the first node in ChildNodes.
NextSibling returns the next sibling node of the current node, or null if the current node is the last node in ChildNodes.
* Operation node:
AppendChild () Inserts the node, and the inserted node acts as the last child node of the parent node. That is, the nextsibling of the inserted node is nulll;
InsertBefore () inserts a node, but InsertBefore ("", "") receives two parameters, the first parameter is the node being inserted, the second parameter is the reference node, and the
After InsertBefore is executed, the inserted node will be inserted as the previous sibling node of the referenced node (that is, previoussibling), and the
second parameter can also be null, thus achieving the same effect as appendchild ().
ReplaceChild () replaces the node, replacechild () receives two parameters, the first parameter is the node to be inserted, the second parameter is the node to be replaced,
the node that is replaced still exists in the document, but loses its position in the document.
RemoveChild () Removes the node, removechild () receives a parameter, which is the node being removed, and the return value of the method is the removed node. The removed node
still exists in the document, but it loses its position in the document.
*document node
Document exists:
document. URL gets the full URL of the current page
Document.domain gets the domain name of the current page
Document.referrer gets the source page address of the current page, if no empty string is returned

3. Custom Data properties in HTML5
HTML5 The addition of a non-standard attribute to the element to add a prefix data-, in order to provide the element with rendering-independent information, or simply for semantic information, can be added casually
Just start with data-. The value of the response can then be accessed through a dataset, and the property name does not have a data-prefix when the dataset is evaluated, if the property is Data-myname
You only need to use Selector.dataset.myname.

4. Three ways to insert markers in HTML5
*innerhtml
In read mode, innerHTML returns the HTML code for all child nodes of the element that called it.
In the write mode, innerHTML receives an HTML code as a parameter, creates a new DOM tree based on the parameters that are developed, and replaces the original DOM tree with the new DOM tree.
*outerhtml
In read mode, outerHTML returns all HTML tags that include the element that called it and all child nodes.
In write mode, it is equivalent to creating a new DOM tree from a parameter, and then replacing the DOM tree that includes calling the method.
The conversion to code is:
Div.outerhtml ("<p>this is text</p>");
var p = document.createelement (' P ');
P.append (document.createTextNode (' This is Text '));
Div.parentNode.replace (P,DIV);
*insertadjacenthtml () method
Receives two parameters, the first parameter is the position to insert, and the second parameter is the element to insert.
The first argument is Beforebegin, which indicates that a sibling element is inserted before the current element.
The first parameter is Afterbegin,???????????????????????????????????????????????????????????????????????????????????????????????????????? ????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????? ????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????? ????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????? ??????????????????????? Said??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????? ????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????? ????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????? ????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????? ?????????????????????????????????????????????????????????????????????????????? Inserts a new child element below the current element, or inserts a new child element before the first child element.
The first argument is beforeend, which means inserting a new child element below the current element or inserting a new child element after the last child element.
The first argument, Afterend, represents inserting an immediate sibling element after the current element.
5. Calculation style in DOM:
Calculation styles in *dom2:
Enhanced Document.defaultView.getComputedStyle ("", "") passed in two parameters, the first argument passed in to evaluate the style of the element, the second parameter is a pseudo-element
The string, if no information is required to obtain a pseudo-element, can pass NULL; the final call is in the form var style = Document.defaultView.getComputedStyle (div,null);
This form takes out the calculated style. Style.backgroundcolor,style.width,style.height.
There is no getcomputedstyle attribute in IE, the currentstyle return type in IE is the same as getComputedStyle, and the call form is Mydiv.currentstyle.

Offset offsets in *cssdom
The size of the space occupied by the offsetwiidth element in the horizontal direction, including the width of the element, the width of the visible vertical scrollbar of the element, and the width of the left and right border.
The offheight element occupies space in the vertical direction, including the height of the element, the width of the scrollbar in the horizontal direction of the element, and the width of the upper and lower border.
The distance between the OffsetTop element Sisu border and the top border of the containing element.
Offsetleft the distance between the left bounding box of the element and the left inner border of the containing element.
OffsetParent refers to the element's outer inclusion element.
A common method of acquiring elements relative to document offsets:
function Getelementleft (Element) {
var left = Element.offsetleft;
var current = Element.offsetparent;
while (current!== null) {
Left + = Current.offsetleft;
current = Current.offsetparent;
}
return left;
}

* Size of client area
ClientWidth:
The width of the element content plus the width of the left and right padding.
ClientHeight:
The height of the element content plus the height of the top and bottom padding
* The size of the element's scroll
The scrollheight represents the total height of the element's content area without a scroll bar.
The scrollwidth represents the total width of the element's content area without a scroll bar.
The scrolltop represents the number of pixels that are hidden above the element because of the presence of the scroll bar. You can use it to change the position of the scroll bar.
ScrollLeft represents the number of pixels that are hidden on the left side of the element due to the presence of scrollbars. You can use it to change the position of the scroll bar.
For example, returns an example of a button at the top.
function Scrolltotop (Element) {
if (element.scrolltop! = 0) {
element.scrolltop = 0;
}
}
* Determine the size of the element
The Getboundingclientrect () method doesn't quite understand, mark.

========================================================================
Summary of events in JS:
1. Event capture and event bubbling

2, DOM2 level Event processing program
Add Event: AddEventListener ()
Delete event: RemoveEventListener ()
They all accept three parameters, the first argument is the event type, the second argument is the event-triggered function, and the third argument is a Boolean type. Ture represents the capture phase
Call the event handler, false to call the event handler during the bubbling phase.
To add an example of an event for a button:
Btn.addeventlistener ("click", Function () {alert ("BTN")},false);
It is important to note that events added through AddEventListener () can only be removed with RemoveEventListener (), and that the parameters they pass in are guaranteed
Must be consistent to delete, all to satisfy this rule, there is a problem, that is, the incoming anonymous function of the event will not be deleted.
Event handlers in IE:
Add Event: attachevent ()
Delete event: DetachEvent ()
They all accept two parameters, the first parameter accepts the event type, and here AddEventListener () does not use event type-based event type,
That is, the event type is all the event type on the start, and the second parameter receives the executing function that is triggered. This method all uses event bubbling to invoke the
Event. It is important to note that the attachevent () execution environment is the global execution environment, so the value of this in attachevent () is window.
3, calculate the mouse position of the event
ClientX: Returns the horizontal axis of the mouse relative to the viewport of the browser.
ClientY: Returns the ordinate of the mouse relative to the viewport of the browser.
PageX: Mouse relative to the horizontal axis of the page.
Pagey: Mouse relative to the ordinate of the page.
ScreenX: The horizontal axis of the mouse relative to the screen.
ScreenY: The vertical axis of the mouse relative to the screen.
4, the mouse wheel scrolling events
MouseWheel event, the mouse wheel scrolling when triggered, there is a Wheeldelta property, depending on the direction of positive and negative, are multiples of 120, so according to the Wheeldelta property
To determine the direction in which the mouse scrolls.
5. Touch and gesture events on the mobile side
Touchstart () triggers when the finger touches the screen.
Touchend () triggers when the finger moves away from the screen.
Touchmove () triggers when the finger slides continuously on the screen.
Touchcancel () triggers when the system stops tracking touch.
Convert NodeList to arrays
var array = Array.prototype.slice.call (nodelist,0);
Convert arguments objects to arrays
var array = Array.prototype.slice.call (arguments,0);
==========================================================
1, the Operation method of the string in JS
CharAt () can pass in an index that returns the character of the string at that index, which can be simplified by adding index values directly in [] brackets to achieve the same effect.
Concat () can concatenate strings and strings together.
Slice () and substring () can pass in one or two parameters, passing in one parameter, returning the first index to the substring at the end of the string. Incoming
The second parameter returns a substring between the first and second indexes.
SUBSTR () returns a substring from the first index to the number of the second parameter when passing in a parameter, as in the top function, when passed in a second argument.
IndexOf () and LastIndexOf () return the index of the given character in the string, IndexOf starts from the beginning, and LastIndexOf starts at the end of the string.
2, the operation method of the array in JS
The join () method takes a parameter, converts the array to a string, and splits it with the parameters passed in.
The push () method takes a parameter, puts the parameter at the end of the array, and returns the length of the modified array.
The Pop () method removes an item from the end of the array and returns the item that is removed.
The shift () method moves the first item of the array and returns the item.
The Unshift () method is added to the array with the first item and returns the length of the modified array.
A very powerful method in the array:
Splice () provides two parameters when it is deleted, that is, the first parameter is the starting item to be deleted, and the number of items to be deleted.
Splice () If three parameters, the second argument is 0 o'clock, that is, the number of items to be deleted is 0, the first argument is the starting item, and can have a third, four, or more arguments, representing the
Dead a parameter entry is inserted after the item, and the second parameter is 0.
If the second parameter is not 0, it is the substitution function, which is to delete the item of the corresponding length from the start item, and then insert the individual items that pass in the parameter later.
3. HTTP Hypertext Transfer Protocol
It is divided into 4 processes:
Establish a connection
Send Request
Send response
Close connection
4, JS in the closure:
Closures are interpreted in the JavaScript advanced programming book as referring to functions that have access to variables in another function scope, and simple explanations can be divided into two types, in functions
As a return value, passed as a parameter.
About scopes: There is no block-level scope in JavaScript, and only functions in JavaScript can declare a scope, and the scope is at the time of the function declaration
is created.
About executing the following: The execution context is real, and the JavaScript program automatically enters the execution context of the global environment when it executes, and is defined in the execution context
A variable that is declared beforehand. Then, each time a function is called, the context execution environment of the function is created in the scope of the function, in the scope of the function itself
Variable to assign a value. When the function finishes executing, the execution context of the function is destroyed.
Again about closures: because closures are functions that reference variables in the scope of another function, when the outer function is called, it is common sense that the function should be destroyed by the
Context execution environment, but because there is also a function in the function that references the variable in that function scope, all if the context of the function's execution environment is destroyed
The function that references the function's scope is not worth the value, so the context execution environment of the function will not be destroyed, so that when the call references the function in the scope of the
variables, their two context execution environment is in memory, which is the closure, which increases overhead.
5, JS in the application of Ajax:
The first steps to use Ajax in JavaScript are:
1. Create a XMLHttpRequest Object
var xhr = new XMLHttpRequest ();
2. Use the open () function to establish a connection to the server:
Xhr.open ("GET", "url", true);
3. Send request with Send () function like server
Xhr.send (NULL);
4. Processing results
The processing result uses the XHR onreadystatechange event to listen for the Xhr.readystate property, which, when the property is 4, indicates that the request was sent successfully.
And there is the data returned. You can manipulate the page according to the data.
Note: When sending a post, you need to send a go-to request header at the same time. To properly use a POST request.
Xhr.setrequestheader ("Content-type", "application/x-www-form-urlencoded");
6, JS in the This object
To summarize a sentence, this always points to the object that called the function.
============================================================
7. What is the difference between objects in JavaScript and other object-oriented languages?
In general, the object-oriented language has the concept of class, and through the class can create any number of objects with the same properties and methods, there is no concept of class in the second JavaScript,
In ECMAScript, an object is defined as a collection of unordered properties whose properties can contain basic values, objects, or functions. In other words, an object is a set of values that do not have a specific order.
Each property and method of an object has a specific name, and each name is mapped to a value.
8, the role of Web semantics:
In order to have no CSS, the Web page can also render a good content structure, code structure.
Enhanced user experience, Title,alt,label label utilization
Facilitates SEO, and the search engine builds good communication, facilitates the crawler to crawl more effective information.
It facilitates the development and maintenance of the team, and is more readable in semantics.
9, IE6 the floating bilateral distance bug:
In IE6, if you set a float for an element and then set the left and right margins for the element, the margin is larger than the actual size in the IE6.
The solution is to add _display:inline to the floating element;
10, CSS to solve the compatibility problem in IE:
Using progressive recognition to solve the problem in IE.
Add \9 at the end to isolate the IE678.
And then add the + in front to separate out the IE67.
And then add _ in front to separate out the IE6.
For example:
. bb{
Background: #ffeedd; all identification
Background: #445566 \9; IE678 can identify
+background: #222222; IE67 can identify
_background: #667788; IE6 can identify
}
11, the universal way to clear the float:
clearfix:after{
Content: '. ';
height:0;
Visibility:hidden;
Display:block;
Clear:both;
}
12. What does the new operator in JS do?
An empty object is created and the This variable is referenced by the object, and the prototype of the function is inherited.

=============================================

1, the BOM object in JS: (Browser object model)
*window object:
The Window object acts as a global object in ECMAScript, and the object defined in the window is automatically added to the global object, but the two objects are still
One small difference is that objects defined on a window can be deleted by the delete operator, and objects directly defined in global cannot be deleted by the delete operator.
The location object of the *window object:
The Location object in the Window object is very common. There are several properties commonly used by Location objects:
Host: Returns the server name and port number
Hostname: Returns the server name without a port number
HREF: the ToString () method that returns the full url,location of the current page returns the same value.
Pathname: Returns the directory name or file name under the URL
PORT: Returns the port number specified in the URL
Search: Returns the query string in the URL (in? The argument string for the opening address bar)
Note: Important methods for parsing query strings
This method is mainly divided into the following steps:
1. Remove the question mark from the beginning.
2. Use split to divide the string into an array with the & symbol (now each element is name=value);
3. Establish the object that will be returned to save the query string.
4, then use for loop traversal, and then "=" split, take the array of 1th and 2nd bits to save the value.
5. Load the value into the object to be returned.
function Getquerystringargs () {
var qstr = (Location.search.length > 0? qstr.substring (1): "");//get rid of the beginning?
var arg = {};
Items = (Qstr.length > 0? qstr.split ("&"): []);
item = NULL;
name = NULL;
value = NULL;
for (var i = 0; i < items.length; i++) {
Item = items[i].split ("=");
name = Item[0];
Value = Item[1];
if (name.length) {

arg[name]= value;
}
}
return arg;
}
The Navigator object in the *window object:
Online detects if the browser is connected to the Internet.
* Use Navigator object to detect browser plugin
Using an array, Window.navigator.plugins gets the array of plug-ins. The name of the plugin can be accessed in the array, and the Decription property.
IE does not support the above method, ie with ActiveXObject detection plug-in.
The history object in the *window object:
The most basic method in the History object is the Go () method:
The Go () method can receive a number as a parameter, the number can be positive (positive indicates forward), or it can be negative (negative means backward),
For example, Window.history.go (1)//Represents a page forward.
Window.history.go (-1)//means pushing backward one page
The Go () method can also receive a string as an argument, and the meaning of the receive string is to jump to the location of the nearest record where the address contains that string.
History is more commonly used in the back () and forward () method, as the name implies, the backward () method is to reverse a page, the forward () method is to move forward a page.
2, the event object in JS
JS generates an event event object when it processes events. The event object retains many of the frequently used properties and methods:
Preventdefault () cancels the default behavior of an event
Stoppropagation The bubbling behavior of canceling events
Target read-only property, which points to the target of the event, and the event caused by bubbling points to the element that caused the event first.
If it does not bubble, it points to the element of the current binding event. Is the same as the object referred to by Currenttarget and this.
3. Simulation Events in jquery
$ (). focus ();
$ (). Click ();
4, the reference type in JS
Object
Array
Date
Regexp
Function
Special Reference types:
Boolean
Number
Some of the methods commonly used in number
The toString () parameter is converted to a number of binary outputs to
The toFixed () parameter is passed in a few points, which is the output of floating-point numbers with several decimal places.
The basic type in JS
Undefined??
Null
?? Boolean
?? Number
String
5, JS in the array of iterations
A feeling of being able to use:
Every ()
Evaluates whether each element in the array satisfies a particular condition, returns True if all is true, or returns false.
Filter ()
Filters the number of the specified condition in the array, returning the satisfied array.
Map ()
Performs a specific method on each element of an array, returning the result arrays after execution
ForEach ()
does not return any value, equivalent to
Some ()
In contrast to every, judging whether each element satisfies a particular condition, returns true if there is a pseudo-true.
Their usage is:
var numbers = [1,2,3,4,5,6,7];
var result = Numbers.filter (function (Item,index,array) {
Return (item > 2);
});
alert (result);//[2,3,4,5,6,7]
6. Browser-compatible Bind Bind event method
function bind (Element,eventtype,callback) {
if (typeof El.addeventlistener = = = ' function ') {
El.addeventlistener (Eventtype,callback,false);
}else if (typeof el.attachevent = = = ' function ') {
El.attachevent (' on ' + eventtype,callback);
}
}
}

7, JS Zhongyuan chain is what?
When accessing an object's properties, look in the basic properties now, if not, and then look up along the _proto_ chain, which is the prototype chain
8, JS in the scope chain
The definition of the scope chain in JS: When the contemporary code executes in the execution environment, a scope chain is created. The purpose is to ensure that all variables and functions that have access to the execution environment are
Orderly access.
The most front end of the scope chain is the variable of the environment in which the current execution code resides
9. Extend the scope chain
The catch statement in the Try-catch statement
With statement
Both statements add an object to the front end of the scope chain, and with the WITH statement, the WITH statement adds the specified object to the scope.
For a catch statement, a new variable object is created that contains the declaration of the thrown error object.
10. Parsing JSON
Json.stringify () parses a JSON object into a string
Json.parse () Converts a string to a JS object
Eval can also implement the same function of parsing JSON into a JS object, but it is not safe to say, so it is seldom used.
11. What is a prototype in JS?
Each function that is created has a prototype property that points to a prototype object that contains all the shared properties and methods of the class object.
This is the prototype.
12. callee in function
How to use: Arguments.callee point to the function that owns the arguments
13. Apply () and call ()
Calls a function in a specific scope.
The real advantage of call () and apply () is that you can extend the scope in which the function is run, and the greatest benefit is that there is no longer any coupling between the object and the method.
The bind () method creates an instance of a function whose value is bound to the parameters of bind ().
14, the HTTP status code is 304, indicating that the requested resource has not been modified, you can directly use the browser cached version.
503, indicating that the server received the request but did not process it. The server may be overloaded or maintained.
403, no access.
15, JS cross-domain issues:
*cors
Using Cors (cross-domain resource sharing) to implement cross-domain, the idea behind this is to use a custom HTTP request header to communicate with the server to determine whether the request is successful or
Failed.
*jsonp
JSON withing padding, which is essentially contained in a function called JSON. (The name of the callback function, typically specified in the request)
Generally divided into two parts,
The actual usage is:
Dynamically create a SCRIPT element that, when used, adds a src attribute to the <script> element, where you can indicate a cross-domain URL.
The JSONP is easy to use and has the advantage of being able to access responsive text and support bidirectional communication between the browser and the server.
* Cross subdomains by modifying document.domain
To solve cross-domain problems in different iframe in the same page, you can take the window property of the IFRAME, but not the properties below window, by
Modifying the document.domain of two pages equals the parent domain name at the top level.
* Using Window.name

* Image Ping
The principle is that a Web page can load images from any page, regardless of cross-domain or cross-domain. Through the image ping, the browser can not get any data,
Instead, you can determine whether the server received a response based on the load and error methods.
Image Ping can only be used for one-way communication between the browser and the server.
*comet
Abbreviated as server push, if Ajax is the way the browser requests data from the server, then comet is how the server pushes the data to the browser.
The way comet is divided into long polling and streaming.
Long polling:
The browser initiates a request to the server, and the server keeps the connection open, sending it to the browser when the data can be sent.
Data, the browser finishes receiving data and closes the connection. The browser then initiates a request, and the process continues.
HTTP streaming: The browser only establishes an HTTP connection with the server, and then the connection is opened, and the server periodically sends the data to the browser,
The client needs to compare the received data to identify what's new.
16. DocType is at the front of the document and tells the browser what mode to render the document.
In promiscuous mode, pages are displayed in a relaxed, backwards-compatible manner. Simulates the behavior of an older browser to prevent the site from working.
17, JS lazy loading mode
* Dynamic creation of scripts
var script = document.createelement ("script");
Script.type = "Text/javascript";
SCRIPT.SRC = "Client.js";
Document.body.appendChild (script);
* Using defer
<script type = "src=" "defer=" defer "></script>
* Using Async
<script type= "" Async src= "" ></script>
18, a sentence to achieve the first letter of the method of capitalization, in addition to using CSS3 in the text-transform:capitalize;
19, JS implementation of the way to inherit
1. Using the prototype chain to inherit
2. Borrowing constructor inheritance
3. Combined inheritance
4. prototype-Type Inheritance
5. Parasitic inheritance
6. Parasitic combined inheritance
20. How to create objects in JS
1. Factory mode
2. Constructor mode
3. Prototype mode

Your own summary of JavaScript basics

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.