JavaScript notes
knowledge
DOM
The Document Object Model is an application programming interface for using extended XML in HTML. DOM abstracts the entire page as a set of hierarchical nodes. Each component of an HTML or XML page is a kind of node that contains different data.Copy the code
BOM
Browser object model, used to support access and manipulation of browser Windows. Using the BOM, developers can control what the browser displays outside of the page.Copy the code
variable
The var keyword
1. varDeclare scope usagevarThe variable defined by the operator becomes a local variable of the function that contains it. For example, usingvarDefining a variable in the content of a function means that the variable will be destroyed when the function exits. Such as:function jsTest() {
console.log(num);
var num = 1;
}
jsTest(); //undefinedThe error is not reported because the ECMAScript runtime sees this as equivalent to code like this:function jsTest() {
var num;
console.log(num);
num = 1;
}
jsTest(); //undefined
2. varDeclaration promotion refers to pushing all variable declarations to the top of the function scope. In addition, use it repeatedlyvarThere's no problem declaring the same variable.Copy the code
Let the keyword
letwithvarIs similar, but with a very important difference. The most obvious difference is that,letThe declared orientation is block scope, whilevarThe declared scope is the function scope.letRedundant declarations are not allowed in the same block of scope. This will result in an error:let name;
let name; // The identifier name is declared
Copy the code
Let is different from var
1.Temporary dead zonelet 与 varThe important difference is thatletDeclared variables are not promoted in scope. As you parse your code, the JavaScript engine also pays attention to what appears after the blockletDeclaration, except that undeclared variables cannot be referred to in any way before then. inletThe moment of execution before a declaration is called a "temporary dead zone," in which references to any variable declared later are thrownReferenceError.2.Global declaration andvarDifferent keywords are usedletVariables declared in global scope do not becomewindowObject properties (varDeclared variables do).var name = "Zhang"; / / zhang SAN
console.log(window.name);
let name = "Zhang"; //undefined
console.log(window.name);
Copy the code
Const statement
Const behaves much the same as let, with the only important differences being that variables declared with it must also be initialized, and attempts to modify a variable declared by const result in a runtime error.Copy the code
The data type
ECMAScript has seven data types, including: six simple data classes (also known as primitive types) : Undefined, Null, Boolean, Number, String, and Symbol. One complex data type is called Object.Copy the code
The element
<script>
The element
Properties:
The main way to insert JavaScript into HTML is to use <script> elements. The <script> element has the following eight attributes: 1. Async: Optional. Indicates that you should start downloading the script immediately, but you cannot prevent other page actions, such as downloading resources or waiting for other scripts to load. Only for external files. 2. Charset: Optional. The code character set specified with the SRC attribute. This property is rarely used because most browsers don't care about its value. 3. Crossorigin: Optional. Configure CORS (Cross-domain resource Sharing) Settings for related requests. COPS is not used by default. Crossorigin = "anonymous" profile requests do not have to set credential flags. Crossorigin = "use-credentials" sets the credential flag, which means that outbound requests contain credentials. 4. Defer: Optional. If the signature of the resource that is allowed to be received does not match the signature specified by this property, an error is reported and the script is not executed. This property can be used to ensure that content distribution networks do not serve malicious content. 4. 5. How to Play guitar 5. Originally used to identify the scripting language (such as "JavaScript", "JavaScript 1.2" or "VBScript") in a code block. Most browsers ignore this property and should never use it again. 6. SRC: Optional. Represents an external file that contains the code to execute. 7. Type: Optional. Instead of language, represents the content type (also known as MIME type) of the scripting language in the code block. By convention, this value is always "text/javascript", although "text/javascript" and "text/ecmascript" are obsolete. The MIME type of a JavaScript file is usually "application/ X-javascript", but giving this value to the type attribute is likely to cause the script to be ignored. Other values that are valid in IE browsers are "application/javascript" and "application/ecmascript". If the value is module, the code is treated as an ES6 module, and only then can the import and export keywords appear in the code. There are two ways to use <script> : 1. Use it to embed JavaScript code directly in a web page; 2. It allows you to include external JavaScript files in your web pagesCopy the code
Dynamically loading scripts
Just create a script element and add it to the DOM.let script = document.createElement('script');
script.src = 'test.js';
document.head.appendChild(script); // Or the body positionResources obtained in this way are not visible to the browser preloader. This can seriously affect their priority in the resource acquisition queue. Depending on how the application works and how it is used, this can have a significant impact on performance. To let the preloader know of the existence of these dynamic request files, declare them in the stable header display: <link rel="preload" href="test.js" />
Copy the code
<noscript>
The element
The <noscript> element is used to provide alternative content to browsers that do not support JavaScript. Although today's browsers are 100% JavaScript oriented, this element is still useful only for browsers that disable JavaScript. <noscript> elements can contain HTML elements where swimsuits can appear in <body>, except for <script>. The browser will display content contained in <noscript> in two cases: 1. The browser does not support scripts. 2. The browser support for scripts is disabledCopy the code
JavaScript
With statement
withThe purpose of the statement is to set the code scope to a characteristic object. usewithThe main scenario for the statement is repeated operations on an object, which scope the code to provide traversal, as follows:const data = {
value: {
name: 'Joe'.age: 20.sex: 'male'}}var user = {
name: data.value.name,
age: data.value.age,
sex: data.value.sex
}
console.log(user); All of the above code has data.value objects, if usedwithStatement, so there is less code:const data = {
value: {
name: 'Joe'.age: 20.sex: 'male'}}with (data.value) {
var user = { name, age, sex }
}
console.log(user);
Copy the code
Array copy and fill methods
ES6 has two new methods: the bulk copy method copyWithin(), and the fill array method fill(). The function signature of both methods is similar in that you need to specify a range on the existing array instance, with the start index and no end index. Using this method does not change the size of the array./* fill */Such as:const datas = [0.0.0.0.0];
// Fill the array with 5
datas.fill(5.1.3);
console.log(datas); // Result [0, 5, 5, 0, 0]
/* copyWithin */Such as:const datas = [0.1.2.3.4.5.6.7];
// Copy the contents of index 0 to 3 and place them at index 2
console.log(datas.copyWithin(2.0.3));
Copy the code
Change the method to which this points
Method 1: Call
/ * * sample * /
const user = {
name: 'Sketchy'
}
function fn(x, y) {
console.log(x, y);
console.log(this.name);
}
fn.call(user, 1.2);
Copy the code
Method 2: Apply
Apply () is very similar to call (), except in the way it provides arguments. Apply () uses an array of arguments instead of a list of arguments/ * * sample * /
const user = {
name: 'Sketchy'
}
function fn(x, y) {
console.log(this.name);
}
fn.apply(user, [1.2]);
Copy the code
Bind
Bind () creates a new function (called a binding function) that has the same function body as the called function when the target function is calledthisThe value of bind is bound to the first argument of bind()/ * * sample * /
const user = {
name: 'Sketchy'
}
function fn(x, y) {
console.log(this.name);
}
fn.bind(user, 1.2); // Only the binding has no output
fn.bind(user, 1.2) ();// bind and output
Copy the code
How objects are created
// 1. Create a new instance of Object and add attributes and methods to it:
let person = new Object(a); person.name ='Sketchy';
person.age = 20;
person.sayName = function() {
console.log(this.name);
}
// 2. Create an object named person with attributes and methods
let person = {
name: 'Sketchy';
age: 20;
sayName() {
console.log(this.name); }}Copy the code
Data attributes
// Data attributes contain a location to hold data values. Values are read from and written to this location. Data attributes have four properties that describe their behavior.
1.[[64x]] : indicates whether the property can pass throughdeleteDelete and redefine, whether its characteristics can be changed, and whether it can be changed to an accessor property. By default, this feature is true for all properties directly defined on an objecttrue, as shown in the previous example.2.[[Enumerable]] : Indicates whether an attribute can passfor-inLoop back. By default, this property is for all attributes defined directly on the objecttrue, as shown in the previous example.3.[[Writable]] : indicates whether the value of an attribute can be modified. By default, this property is for all properties directly defined on an objecttrue, as shown in the previous example.4.[[Value]] : contains the actual Value of the attribute. This is where the property values are read and written as mentioned earlier. The default value for this feature isundefined.// To change the default properties of a property, you must use the object.defineProperty () method:This method receives3Three arguments: the object to which the attribute is to be added, the name of the attribute, and a descriptor object. The last parameter, a property on the descriptor object, can contain different parameters, Enumerable, Writable, and Value, which correspond to the name of the different feature./ / sample:
let person = {};
Object.defineProperty(person, "name", {
writable: false.value: "Nicholas"
});
console.log(person.name); // "Nicholas"
person.name = "Greg";
console.log(person.name); // "Nicholas"
// Define multiple attributes
let book = {};
Object.defineProperties(book, {
year_: {
value: 2017
},
edition: {
value: 1
},
year: {
get() {
return this.year_;
},
set(newValue) {
if (newValue > 2017) {
this.year_ = newValue;
this.edition += newValue - 2017; }}}});Copy the code
Merging of objects
// ES6 provides the object.assign () method specifically for merging objects
// The method receives a target object and one or more source objects
// If multiple source objects have the same attribute, the last copy is used
const obj1 = {
id: 1
}
const obj2 = {
name: 'Sketchy'
}
const obj3 = {
age: 20
}
const result = Object.assign(obj1, obj2, obj3);
console.log(result === obj1); //true
console.log(result === obj2); //false
console.log(result === obj3); //false
Copy the code
Object identification and equality determination
// Prior to ES6, some special cases occurred that the === operator could not handle
// To improve this situation, ES6 adds object.is (). This method, much like ===, takes two arguments
Copy the code
Agency and reflection
The agent
The proxy usesProxyConstructor. This constructor takes two parameters: the target object and the handler object. Missing any of these arguments is thrownTypeError. To create an empty proxy, you can pass a simple object literal as a handler object, allowing all operations to reach the target object unimpeded.const person = {
name: 'Sketchy'
}
const handle = {}
const proxy = new Proxy(person, handle);
// Assigning a target attribute is reflected on both objects
// Because both objects access the same value
proxy.id = 1;
console.log(proxy.id);
console.log(person.id);
Copy the code
Define trap
The main purpose of using proxies is that you can define traps. A catcher is an "interceptor for basic operations" defined in a handler object. Each handler object can contain zero or more traps, each of which corresponds to a basic operation that can be invoked directly or indirectly on a proxy object. Each time these basic operations are invoked on a proxy object, the proxy can intercept and modify the corresponding behavior by calling the catcher function before the operations are propagated to the target object.const person = {
name: 'Sketchy'
}
const handle = {
get() {
return 'Hello'; }}const proxy = new Proxy(person, handle);
console.log(person.name); / / have slightly
console.log(proxy.name); // HelloAll catchers have access to parameters based on which the original behavior of the captured method can be reconstructed. For example, the GET () trap receives the target object, the property to be queried, and the proxy object.const handle = {
get(trapTarget, property, receiver) {
returntrapTarget[property]; All catchers can reconstruct the original operation based on their parameters, but not all catchers behave as simply as get(). Therefore, the idea of doing the same by writing code by hand is unrealistic. In fact, developers don't need to manually recreate the original behavior, but can call it globallyReflectA method of the same name on the object (which encapsulates the original behavior) for easy reconstruction. It could even be written more succinctly:const handle = {
get: ReflectIn fact, if you really wanted to create an empty proxy that could catch all methods and then forward each method to the corresponding reflection API, you wouldn't even need to define a handler object:const proxy = new Proxy(person, Reflect);
Copy the code
Revocable agency
Sometimes it may be necessary to break the connection between the proxy object and the target object. For the use ofnew ProxyFor ordinary proxies created by (), this connection persists for the lifetime of the proxy object.ProxyAlso exposed is the Revocable () method, which supports unassociating proxy objects with target objects. Revoking an agent is irreversible. Furthermore, the revoke function () is idempotent, yielding the same result no matter how many times it is called. A call to the proxy after it has been revoked throwsTypeError.const person = {
name: 'Sketchy'
}
const handle = {
get: Reflect.get,
}
const { proxy, revoke } = Proxy.revocable(person, handle);
revoke();
console.log(person.name);
console.log(proxy.name); / / an error
Copy the code
new.target
Functions in ECMAScript can always instantiate a new object as constructors or be called as normal functions. ECMAScript6Added check whether function is usednewKey words usednewThe target attribute. If the function is called normallynew. The target value isundefined; If you are usingnewIf the keyword is used, thennew.target will refer to the constructor being called.function King() {
if (!new.target) {
throw 'No call to new'
}
console.log('Called with new');
}
new King(); // call with new
King(); // No new call is used
Copy the code
BOM
Navigate and open a new window
The window.open() method can be used to navigate to a specified URL or to open a new browser window. This method takes four parameters: the URL to load, the target window, a property string, and a Boolean value indicating whether the new window replaces the currently loaded page in the browser history. Normally, only the first three arguments are passed when this method is called, and the last argument is used only when no new window is opened. If the second argument to window.open() is the name of an existing window or frame, the URL is opened in that window or frame.Copy the code