In each environment, some features of the current environment will also be developed based on JS, such as global objects in NodeJS, process objects in the browser environment, Window objects, document objects, etc., which belong to the js based content of the runtime environment. Require is part of the nodeJs specific runtime environment and cannot be used on the browser side.
Browser built-in Objects
window
Window represents the global scope in the browser. All variables and contents declared in the global scope will eventually become properties of the Window object, such as:
var num = 123;
console.log(window.num) / / 123
Copy the code
If you access an undeclared variable directly, you get an error, and if you access it using a window, as if it were an object, undefined is returned.
var name = oldName; Uncaught ReferenceError: oldName is not defined var name2 = window.oldname; // Uncaught ReferenceError: oldName is not defined var name2 = window.oldname; // undefinedCopy the code
SetTimeout and setInterval
They both take two arguments. The first argument is a callback function, and the second argument is the time to wait for execution. When the wait time is over, the callback function is placed in an event loop for execution. Passing in clearTimeout and clearInterval clears this scheduled operation.
var id = setTimeout(function() {
console.log('hello world')},2000)
clearTimeout(id);
Copy the code
If there is no content in the queue, then the callback function will be executed. If there is content in the queue, then the callback function will be executed after the content is finished.
Because setInterval execution time is uncertain, most of the time, we will use setTimeout to simulate
Use setTimeout to simulate the completion of each execution and then push the next event into the event queue
Location
Properties: juejin. Cn/editor/draf… Hash: hash
Host: The host name and port to return the URL
Hostname: indicates the hostname
Port: the port
Href: indicates the current URL
The pathname: url path name Such as: / editor/drafts / 6908977883482587149
Protocol: INDICATES whether the URL protocol is HTTP or HTTPS
Serch: Query part of the URL query=string
Reload: reloads the current page
Replace: Replace the page following the current domain name with a new page
Document
Method: selector
The selector is the most important to investigate the browser related knowledge, generally combined with the actual scene to investigate.
GetElementById, getElementsByClassName, getElementsBytagName and other apis defined by the earlier specification, as well as the new specification added selectors such as querySelector querySelectorAll
Important: Functions such as getElementsByTagName that return multiple nodes are not arrays, but rather data structures implemented by browsers.
Object.prototype.toString.call(document.getElementsByTagName('i')) // [object HTMLCollection]
Copy the code
Method: Create the element
Document. createElement creates a DOM element. When adding multiple elements, you can first concatenate all the DOM elements in memory and then insert them once.
var fruits = ['Apple'.'Orange'.'Banana'.'Melon'];
var fragment = document.createDocumentFragment(); // Create a virtual node object
fruits.forEach(fruit= > {
const li = document.createElement('li');
li.innerHTML = fruit;
fragment.appendChild(li);
});
document.body.appendChild(fragment);
Copy the code
attribute
-
Title: Document. title sets or returns the title of the current page
-
Domain: displays the domain name of the current website
-
Url: The link to the current site
-
Anchors: Returns all anchors, an A tag with the name attribute
-
Forms: returns a collection of all form tags
-
Images: returns a collection of all IMG tags
-
Links: Returns all a tags with href attributes
Element
Element elements have nodeType 1, and most tags are an Element instance
attribute
TagName: returns the tagName of the current element
methods
-
GetAttribute: Obtains the attribute result of the current node
-
SetAttribute: sets the attributes of the current node
The Text type
The Text type contains all plain Text content, does not support child nodes, and has a nodeType of 3
History
The History object contains the URLS that the user has visited (in the browser window). In HTML 5, history is also related to client-side routing information.
attribute
Length: Returns the number of urls in the history list
methods
Back: Loads the previous URL in the history list
Forward: Loads the next URL in the history list
Go: Loads a specific page in the history list
PushState: Replaces the address bar address and adds it to the history list without refreshing the page
ReplaceState: Replace the address bar address, replace the current page in the history list, do not refresh the page
Conclusion:
- Globally defined variables can be accessed through Windows. With setInterval, be aware that it is possible that the code does not execute at the same interval. With aN API like Alert, be aware that JS code can be blocked.
- The Location object needs to specify what value each type represents for the URL.
- The Document object basically connects JS to our DOM element. Note that many of the choices here result in array-like elements. And optimizations such as the createFragment code snippet are used to prevent performance problems caused by multiple browser reorders.
- Element and Text are two common DOM objects that are easy to test and use. Familiar with common methods and debug mode (console.dir). Secondly, when writing code, we need to make clear whether our current method is JS level or environment level.
- History Because it’s related to front-end routing, we need to be familiar with the new pushState and replaceState methods.
The event
We can define an event for a DOM element in several ways:
The first is to add it directly to the DOM element, but this approach is generally not recommended because it overly coupling the view to the logical part of the code.
<script>
function showAlert() {
alert('hello event');
}
</scripts>
<p onclick="showAlert()">Click and alert pops up</p>
Copy the code
The second, purely JS solution, is to get the DOM element by setting its onclick property
document.getElementsByTagName('p') [0].onclick = function() {
alert('hello world');
}
// Cancel the event by setting the onclick property to null
document.getElementsByTagName('p') [0].onclick = null;
Copy the code
- Advantages: Pure JS implementation, view and logic decoupled.
- Disadvantages: A DOM element can only set one onclick event
The third way, pure JS solution, DOM2 level specification to implement the new API, addEventListener and removeEventListener two apis
var onClickFunc = function() {
alert('hello world');
};
document.getElementsByTagName('p') [0].addEventListener('click', onClickFunc);
// To cancel the event, use removeEventListener
document.getElementsByTagName('p') [0].removeEventListener('click', onClickFunc);
Copy the code
-
Advantages:
1, pure JS implementation, view and logic decoupling;
The addEventListener allows you to set multiple event callbacks for click, which are fired in turn
-
Disadvantages:
RemoveEventListener must keep the same function reference as when setting the event, so try not to use anonymous functions when setting the event.
Event capture and bubble
The DOM is a nested tree structure, and the performance in the browser is superimposed, so clicking on a region in the browser will traverse multiple DOM successively in the DOM structure, from the top down we call “event capture”, and from the bottom up we call “event bubble”.
The DOM2 event specification states that a standard flow of events is divided into three phases. First is the “event capture” state from the top down, then the element that actually triggers the event, and finally the “event bubble” from that element back to the top.
The new event definition function addEventListener, which is added to the DOM2-level event specification, uses a third parameter to specify whether to fire an event in the capture phase or to fire an event in the bubble phase. If the third argument is true it fires during the capture phase, and if the third argument is false it fires during the bubble phase.
AttachEvent in IE does not support the capture or bubble phase selection. It can only be triggered during the bubble phase.
The event object
After the event is fired, the browser passes an event object into the event callback itself.
document.getElementsByTagName('p') [0].onclick = function(event) {
console.log(event);
alert('hello event');
};
document.getElementsByTagName('p') [0].addEventListener('click'.function(event) {
console.log(event);
})
Copy the code
Properties under the event object
- Bubbles: Indicates whether or not an event bubbles
- Cancelable: indicates whether the default behavior of an event can be cancelled
- CurrentTarget: The element that the event is currently processing
- Defaultaim: true means it has been called
- PreventDefault function detail: Event details
- EventPhase: The phase in which the event is in. 1 is capture, 2 is at the event target, and 3 is bubbling
- Type: Event type (click, etc.)
Method under the event object
- PreventDefault: cancel the default action of the event
- StopImmediatePropagation: further cancellation event capture or bubble, at the same time to prevent the event handler is called
- StopPropagation: Cancels further capture or bubbling of events
If an event is defined by the DOM0 specification, it is obtained by window. If an attachEvent event is defined, it is also passed in the callback function.
var btn = document.getElementById('btn');
Btn.onclick = function() {
var event = window.event;
};
Copy the code
IE under the event attribute method
- CancelBubble: Default to false, set to true and cancel event bubble
- ReturnValue: The default value is true. Setting false cancellations the default event behavior
- SrcElement: The target of the event
- Type: indicates the type that is triggered
Event delegation
<ul id="ul">
<p>1234</p>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
document.getElementById('ul').onclick = function(event) {
var target = event.target;
if (target.nodeName.toLowerCase() === 'li') { alert(target.innerHTML); }}Copy the code
Universal model
The general event model is mainly to accommodate the differences between the Settings of multiple DOM levels and the differences between IE and mainstream specifications, as well as the content of the event itself.
var addEvent = function(element, eventType, handler) {
if (element.addEventListener) {
element.addEventListener(eventType, handler, false);
} else if (element.attachEvent) {
element.attachEvent('on' + eventType, handler);
} else {
element['on'+ eventType] = handler; }}var removeEvent = function(element, eventType, handler) {
if (element.removeEventListener) {
element.removeEventListener(eventType, handler, false);
} else if (element.detachEvent) {
element.detachEvent('on' + eventType, handler);
} else {
element['on' + eventType] = null; }}var getTarget = function(event) {
return event.target || event.srcElement;
}
var preventDefault = function(event) {
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false; }}var stopPropagation = function(event) {
if (event.stopPropation) {
event.stopPropation();
} else {
event.cancelBubble = true; }}Copy the code