1. What is scope

Common scopes can be divided into several types: global scope, functional scope, block scope and dynamic scope.

object type
global/window Global scope
function Function scope (local scope
{} Block scope
this Dynamic scope

A variable or other expression is not “currently scoped,” and the JavaScript mechanism continues to look up the scope chain until the global scope (global or window in the browser) is unusable if it is not found. Scopes can also be layered by code hierarchy so that the child scope can access the parent scope, usually by looking up variables and references from the child scope along the chain of scopes without being able to refer to the child scope from the parent

1.1 Global scope

A variable defined outside a function or code block {} is a global scope. However, variables that are not defined within a function or code block {} also have global scope.Copy the code
var name = "Sheep";  
// The name variable can be called here
function myFunction() {     
    // The name variable can be called inside the function
}

Copy the code
In the above code, the variable name is defined outside the function and has global scope. This variable can be read or modified anywhere, but if the variable is not declared in the function (without using the var keyword), it is still a global variable.Copy the code
// The name variable can be called here
function myFunction() {      	
    name = "Sheep";    
    // The name variable can be called here
}

Copy the code
In the example above, name is inside the function, but has global scope. It will exist as an attribute of global or Window. To verify the property of window, delete XXX in the console, returning true if it is a property of Window, false otherwise.Copy the code

Variables that are not defined inside a function or in a code block are actually window/global attributes, not global variables. In other words, variables that are not defined using var have global scope but can be deleted, whereas global variables cannot.

1.2 Function scope

Variables defined inside a function are called local scopes. Function scope inside, outside is closed, from the outer scope can not directly access function scope inside. In function scope, novarThe variable must be global. * In function scope, usevarA defined variable raises the declaration to the top of the function scope, but does not call the function.Copy the code
fn();
function fn() {
    console.log('hi');
}
// Result: the console prints the string hi
// Note: the function declaration represents the whole function, so when the function is promoted, the function name represents the whole function, but the function is not called.
Copy the code
// Function expression creates a function that performs a variable promotion, so the variable name of the receiving function cannot be called correctly
fn();
var  fn = function() {
    console.log('hello');
}

Fn is not a function
// This code will be upgraded to undefined before it is executed. Fn is called before fn is assigned to the function body, in which case fn is undefined, so it cannot be called correctly
Copy the code

2.Let & Const

2.1 Let declared variables have block-level scope

{   
    let a = 1 
} 
console.log(a); //undefined

Copy the code

Tip: The a variable is defined in the code block {} using let. It is scoped inside the code block and cannot be accessed externally.

2.2 Global variables declared by let are not properties of global objects

The global variables declared by var are properties of window and can be accessed through window. Variable name.Copy the code
var a = 1 
console.log(window.a); / / 1

Copy the code
let a = 1 
console.log(window.a); // undefined

Copy the code

2.3 Redefining a variable with let throws a syntax error

Var can be defined repeatedly, but let cannot.Copy the code
var a = 1 var a = 2 
console.log(a)  / / 2

Copy the code
let a = 1 
let a = 2 // Uncaught SyntaxError: Identifier 'a' has already been declared

Copy the code

2.4 Variables declared by let do not undergo variable promotion

function test () {   
    console.log(a)   
    var a = 1 
} 
 
test() //undefined

Copy the code
In the above code, a is called before the declaration, so its value is undefined instead of Uncaught ReferenceError. In fact, since var causes the variable to be promoted, the above code is equivalent to the above code:Copy the code
function test () {   
    var a   
    console.log(a)   
    a = 1 
} 
Copy the code

3, arrays,

Array traversal

  • Normal for loop

    Both break and continue are supported

const array=[1.2.3.4.5]
for(var i =0; i < array.length; i++){       			console.log(array[i]);
}
Copy the code
  • Array forEach ()

    The syntax is concise and does not require an index to access an array item. However, its disadvantages are obvious: it does not support break, continue, etc.

array.forEach(function(i){  
    console.log(i);
})


// If you want to iterate through the array, you'll end up with the item 3, or you'll print out all the items you've iterate through
[1.2.3.4.5].forEach(function(i){
    if(i===3) {return;
    }else{    
        console.log(i); }})// output: 1,2,4,5
Copy the code

[!DANGER] forEach code block cannot use break, continue, it will throw an exception

  • Array every ()

    Use every to do the same as break, simply saying return false equals break and return true equals continue.

[1.2.3.4.5].every(function(i){
    if(i===3) {return false;
    }else{    
        console.log(i);
        return true; }})Copy the code

[!DANGER] Every block cannot use break or continue, it will throw an exception.

  • for… in

    You can use for in to manipulate enumerable as well as arrays.

    It is common to iterate over an object’s key name with for in.

    Both break and continue are supported.

var enum = {
    a:1.b:2.c:3.d:"sheep"
};  
for(let item in enum) {  
    console.log(item,enum[item]);  
} 

Copy the code
  • for… of

    For of traverses only the elements of the array, excluding the array’s prototype property Method and index name

var arr=[1.2.4.5.6.7]
arr.name="sheep";
for (var value of arr) {
  console.log(value);
}
Copy the code

4. Type conversion

String length: variable. Length Specifies the number of characters in the string0When performing multiplication, division and subtraction operations, string data is implicitly converted to numeric data before calculation. The result is also numeric data. When you add string data, it's a concatenation of strings and when you add string data to any type of data it's a concatenation BooleantrueCan be converted to a numeric type1.falseCan be converted to a numeric type0Adding string data to any type of data is concatenationCopy the code

5, functions,

5.1 How functions are declared

(1) Named functions: named functions, functions with function names

Named functions are defined as follows:1.How a function name is definedfunctionThe function name (){}
2.The way a function is expressedvar sum = function(){}, the call must be after the definition, otherwise an error will be reported// How to define a function name
function fn(){
    alert('How to define a function name');
}
			

// Function expression
//sum(); / / an error
var sum = function (a,b){
    //alert(' function expression mode ');
    return a+b;
}
//sum();
Copy the code

(2) Anonymous functions: functions without function names. You can’t define it directly

The way anonymous functions are defined:1.Defined as a function expression2.Defined as a self-calling function, a self-calling function is called as soon as it is defined and can only be used once3.Pass as a parameter4.As an event handler5.As a return value/ / error
//	function(){		
/ /}
(function(){
    alert('Function call 1'); }) (); (function(){
    alert('Function call 2'); }) ();Copy the code

5.2 The number of parameters and arguments of a function does not match

Note: In JavaScript, the default value of a parameter is undefined.Copy the code
  • A function can take arguments or no arguments
  • When declaring a function, the parameters inside the parentheses are parameters that default to undefined
  • When you call a function, the arguments inside the parentheses are arguments
  • Multiple parameters are separated by commas
  • The number of parameters may not match the number of arguments, but the result is unpredictable, so we try to match

5.3 Differences between Break, Continue, and Return

  • Break: to end the body of the current loop (for, while)
  • Continue: To break out of the current loop and continue with the next loop (for, while)
  • Return: Not only can you exit the loop, you can also return the value of the return statement, and you can also end the code inside the current function

5.4 Use of arguments

You can use arguments to get arguments when you are unsure how many arguments to pass. In JavaScript, arguments is actually a built-in object for the current function. All functions come with a built-in arguments object, which stores all arguments passed. Arguments presentation form is a pseudo-array, so it can be iterated over. Pseudo-arrays have the following characteristics:

  • Has the length property

  • Store data by index

  • Methods push, pop, etc. without arrays

    Note: This object is used inside a function to get the arguments passed when the function is called.

5.5 Constructors and primitives

5.5.1 Three ways to create an object

  1. Literal mode

    var obj = {};
    Copy the code
  2. The new keyword

    var obj = new Object(a);Copy the code
  3. Constructor mode

    function Person(name,age){
      this.name = name;
      this.age = age;
    }
    var obj = new Person('sheep'.23);
    Copy the code

5.5.2 Constructor Prototype prototype

Constructors The functions assigned by the stereotype are shared by all objects.

JavaScript states that each constructor has a Prototype property that points to another object. Note that prototype is an object whose properties and methods are all owned by the constructor.

We can define those immutable methods directly on a Prototype object so that all object instances can share them.

function Star(uname, age) {
    this.uname = uname;
    this.age = age;
}
Star.prototype.sing = function() {
	console.log('I can sing');
}
var ldh = new Star('Andy Lau'.18);
var zxy = new Star('Jacky Cheung'.19);
ldh.sing();// I can sing
zxy.sing();// I can sing
Copy the code

5.5.3 Object prototype

All objects have a __proto__ attribute that points to the prototype object constructor. We can use the constructor's properties and methods because the object has a __proto__ prototype. __proto__ object prototype is the same as the prototype object prototype. The point of __proto__ object prototype is to provide a direction, or a route, for the object search mechanism, but it is a nonstandard property and therefore cannot be used in actual development. It just points internally to the prototype object prototypeCopy the code

5.5.4 Constructor Constructor

Both __proto__ and prototype objects have a constructor property inside. Constructor we call it a constructor because it refers back to the constructor itself. Constructor is used primarily to record which constructor the object refers to, and it can redirect the prototype object to the original constructor. In general, the methods of the object are set in the prototype object of the constructor. If we have methods for more than one object, we can assign to the prototype object as an object, but this overwrites the original contents of the constructor prototype object so that the modified constructor object no longer points to the current constructor. At this point, we can add a constructor pointing to the original constructor in the modified prototype object.Copy the code

If we modify the original stereotype object and assign the stereotype object to an object, we must manually use constructor to refer back to the original constructor as follows:

 function Star(uname, age) {
     this.uname = uname;
     this.age = age;
 }
 In many cases, we need to manually refer back to the original constructor using the constructor property
 Star.prototype = {
 // If we modify the original stereotype object and assign the stereotype object to an object, we must manually use constructor to refer back to the original constructor
   constructorSing: function() {sing: function() {console.log('I can sing');
   },
   movie: function() {
     console.log('I'll be in a movie.'); }}var zxy = new Star('Jacky Cheung'.19);
console.log(zxy)
Copy the code

As a result of the above code running, set the constructor property as shown below:

If the constructor property is not set, as shown:

5.5.5 prototype chain

Each instance object has a __proto__ attribute that points to the constructor's prototype object, which is also an object that also has a __proto__ attribute, so that layer by layer the prototype chain is formed.Copy the code

5.5.6 Trigonometric relationship between constructor instance and prototype object

1.The constructor's Prototype property points to the constructor prototype object2.The instance object is created by the constructor, and the __proto__ attribute of the instance object points to the constructor's prototype object3.Constructor of the prototype objectconstructorProperty refers to the constructor, the prototype of the instance objectconstructorProperty also points to the constructorCopy the code

5.5.7 Search mechanism of prototype chain and members

Any object has a prototype object, that is, the prototype property. Any prototype object is also an object, and that object has a __proto__ property.

When accessing properties (including methods) of an object, you first look up whether the object itself has the properties. If not, look for its prototype (that is, the prototype object __proto__ points to). If not, find the prototype of the prototype Object (Object's prototype Object). And so on until Object is found (null). The point of __proto__ object archetypes is to provide a direction, or a route, for the object member lookup mechanism.Copy the code

5.5.8 This points to the prototype object

This in the constructor and this in the prototype object refer to our new instance object

function Star(uname, age) {
    this.uname = uname;
    this.age = age;
}
var that;
Star.prototype.sing = function() {
    console.log('I can sing');
    that = this;
}
var ldh = new Star('Andy Lau'.18);
// 1. In the constructor, this refers to object instance LDH
console.log(that === ldh);//true
// 2. This in the prototype object function refers to LDH
Copy the code

5.5.9 Built-in methods for array extension through prototypes

 Array.prototype.sum = function() {
   var sum = 0;
   for (var i = 0; i < this.length; i++) {
   sum += this[i];
   }
   return sum;
 };
 Sum () = sum(); sum() = sum()
Copy the code

5.6 inheritance

5.6.1 call ()

  • Call () can call functions
  • Call () can modify the reference to this. When call() is used, the first parameter is this, and the second parameter is 3. Use commas to separate connections
 function fn(x, y) {
     console.log(this);
     console.log(x + y);
}
  var o = {
  	name: 'andy'
  };
  fn.call(o, 1.2);// This refers to object O,
Copy the code

5.6.. The child constructor inherits attributes from the parent constructor

  1. Start by defining a parent constructor
  2. Define a child constructor
  3. The child constructor inherits the attributes of the parent constructor (using the call method)
 // 1. Parent constructor
 function Father(uname, age) {
   // This points to an object instance of the parent constructor
   this.uname = uname;
   this.age = age;
 }
  // 2. Child constructor
function Son(uname, age, score) {
  // This points to an object instance of the child constructor
  3.Father.call();this, uname, age);
  this.score = score;
}
var son = new Son('Andy Lau'.18.100);
console.log(son);
Copy the code

5.6.3 Borrow the prototype object inheritance method

  1. Start by defining a parent constructor
  2. Define a child constructor
  3. The child constructor inherits the attributes of the parent constructor (using the call method)
// 1. Parent constructor
function Father(uname, age) {
  // This points to an object instance of the parent constructor
  this.uname = uname;
  this.age = age;
}
Father.prototype.money = function() {
  console.log(100000);
 };
 // 2. Child constructor
  function Son(uname, age, score) {
      // This points to an object instance of the child constructor
      Father.call(this, uname, age);
      this.score = score;
  }
// Son.prototype = Father.prototype; This is problematic because if you change the child, the parent will change as well
  Son.prototype = new Father();
  If you modify a prototype object in the form of an object, remember to use constructor to refer back to the original constructor
  Son.prototype.constructor = Son;
  // This is a subconstructor specific method
  Son.prototype.exam = function() {
    console.log('Kids have tests');

  }
  var son = new Son('Andy Lau'.18.100);
  console.log(son);
Copy the code

The code result is shown in the figure above:

6. Browser compatibility

6.1 Different Browser versions

  • Advanced Browser: Chrome Firefox IE9 or above
  • Earlier versions: Internet Explorer 6 7 8

6.2 Compatibility Encapsulates innerText and textContent

The innerText property was created by Microsoft for Internet Explorer, and has since been widely used in all browsers, but it was not available in an earlier version of Firefox. The textContent property is a later property that acts like innerText and is available to all advanced browsers but not to older ones.

// Let all advanced browsers use textContent and lower versions of Ie use innerText
/** * compatibility encapsulates reading element contents * @param {element object} obj */
function getTextContent(obj){
	if(obj.textContent){
		//alert(' advanced browser ');
		return obj.textContent;
	}else{
	//alert(' low-level browser ');
	returnobj.innerText; }}/** * Compatibility encapsulates set element content * @param {element object} obj * @param {text content} TXT */
function setTextContent(obj,txt){
	if(obj.textContent){
        //alert(' advanced browser ');
        obj.textContent = txt;
	}else{
		//alert(' low-level browser ');obj.innerText = txt; }}Copy the code

6.3 Compatibility Encapsulates event listening for elements

Element object. AddEventListener (‘ event type without ON ‘, event handler, Boolean);

  • Boolean value :false event bubble,true event capture
  • Supports binding multiple event types to the same element, only supported in advanced browsers

Element object. AtachEvent (‘ event type with ON ‘, event handler);

  • Only Internet Explorer 10 and later are supported. In Internet Explorer earlier versions, multiple event types bound to the same element are executed in reverse order.
/** * Compatibility encapsulation adds event listener * @param {element} obj * @param {event type} type * @param {event handler} fn * @param {Boolean :false event bubble,true event capture} bool * /
function addEvent(obj, type, fn, bool) {
	if (obj.addEventListener) {
          / / senior
          obj.addEventListener(type, fn, bool)
     } else {
		 / / low
          obj.attachEvent('on' + type, fn)
	}
}


/** * Compatibility encapsulates the element release event listener * @param {Object} obj * @param {Object} type * @param {Object} fn @param {Object} bool */
function removeEvent(obj,type,fn,bool){
	if(obj.removeEventListener){
		obj.removeEventListener(type,fn,bool);
	}else{
		obj.detachEvent('on'+type,fn); }}Copy the code

7, events,

7.1 Three stages of an event

1. Event capture phase: From outside to inside, event capture is the rule 2 made by Netscape for browsers. Event target stage: triggered that element 3. Event bubble stage: from inside to outside, event bubble is by Microsoft to ie browsing rules

The event captures the event target and bubbles from the event targetCopy the code
  • Element. On event mode can only be the default event bubbling process

  • AddEventListener (‘click’, event handler,true);

    The third argument: false is the event bubble phase,ture is the event capture phase

7.2 Registration Events (Two Methods)

7.3 Event Monitoring

AddEventListener () Event listener (supported after IE9)

EventTarget. AddEventListener () method specifies the listeners registered to the eventTarget (target), when the object trigger event is specified, the event handler should be executed.

AttacheEvent () Event Listener (supported by IE678)

The eventTarget.attachevent () method registers the specified listener with the eventTarget (the target object), and when that object fires the specified event, the specified callback function is executed.

</button> <button>ie9 attachEvent</button> <script> var BTNS = document.querySelectorAll('button'); BTNS [0]. Onclick = function() {alert('hi'); } btns[0].onclick = function() { alert('hao a u'); } // the event type is string must be quoted without on // (2) the same element of the same event can add multiple listeners (event handlers) btns[1].addEventListener('click', function() { alert(22); }) btns[1].addEventListener('click', function() { alert(33); }) // 3. AttachEvent ('onclick', function() {alert(11); }) </script>Copy the code

Event listening compatibility solution

Encapsulate a function that determines the browser type:

7.4 Deleting an Event (Unbinding Event)

<div>1</div> <div>2</div> <div>3</div> <script> var divs = document.querySelectorAll('div'); divs[0].onclick = function() { alert(11); Divs [0]. Onclick = null; divs[0]. Divs [1].adDeventListener ('click', fn) function fn() {alert(22); divs[1].removeEventListener('click', fn); } // 3. detachEvent divs[2].attachEvent('onclick', fn1); function fn1() { alert(33); divs[2].detachEvent('onclick', fn1); } </script>Copy the code

** Remove event compatibility solution **

7.5 DOM event flow

The tags in HTML are nested within each other. We can think of elements as a box inside a box, and the document is the big outer box. When you click on a div, you also click on the parent element of the div, or even the entire page. Do you execute the parent element click event first, or the div click event first?Copy the code

For example, we registered a click event for a div on the page, and when you click div, you click Body, you click HTML, and you click Document.

IE proposes to start with the target element and then receive and respond to the event layer by layer, a bubbling event stream. Netscape proposed to start at the outermost layer and then receive and respond to events, layer by layer, in what is called a captured event stream. In the end, the W3C took a middle ground and settled on a common standard -- capture first, bubble later. Modern browsers follow this standard, so when an event occurs, it goes through three phases.Copy the code

The DOM event flow goes through three stages:

  1. Capture phase

  2. Current target stage

  3. Bubbling phase

If we throw a stone into the water, it will first have a descent process, which can be understood as the capture process from the topmost layer to the most specific element of the event (the target point); Bubbles are then created and float to the surface of the water after the lowest point (the most specific element), a process equivalent to event bubbling.

The event bubbling

<div class="father"> <div class="son"> Son box </div> </div> <script> // onclick and attachEvent (IE) trigger // bubble stage in bubble stage // son -> father ->body -> HTML -> document var son = document.querySelector('.son'); Son.addeventlistener ('click', function() {alert('son'); }, false); Var father = document.querySelector('.father'); father.addEventListener('click', function() { alert('father'); }, false); / / to the document register click event, omitting the third parameter document. AddEventListener (' click ', function () {alert (' document '); }) </script>Copy the code

Event capture

<div class="father"> <div class="son">son box </div> </div> <script> // If the third addEventListener() argument is true then // is fired in the capture phase document -> html -> body -> father -> son var son = document.querySelector('.son'); Son.addeventlistener ('click', function() {alert('son'); }, true); var father = document.querySelector('.father'); AddEventListener ('click', function() {alert('father'); }, true); / / to the document register click event, third parameter to true document. The addEventListener (' click ', function () {alert (' document '); }, true) </script>Copy the code

7.6 Event Objects

What is an event object

After an event occurs, the collection of information data related to the event is put into this object, which is the event object.

Such as:

  1. Who bound this event.

  2. When the mouse triggers an event, it gets information about the mouse, such as its position.

  3. When the keyboard triggers an event, it gets information about the keyboard, such as which key was pressed.

Use of event objects

Event objects are generated when an event firing occurs and are passed by the system as arguments to the event handler.

Therefore, declare a parameter in the event handler to receive the event object.

Event object compatibility handling

The event object itself has compatibility issues:

  1. In standard browsers, the parameters passed by the browser to the method can be obtained by defining parameter E.

  2. In IE6~8, the browser does not pass parameters to methods. If necessary, you need to go to window.event to look for them.

As long as the "| |" in frontfalse, no matter "| |" behind ittrueorfalseBehind, return "| |" value. As long as the "| |" in fronttrue, no matter "| |" behind ittrueorfalseIn front of, return "| |" value.Copy the code
<div>123</div> <script> var div = document.querySelector('div'); Div. The onclick = function (e) {/ / event object e = e | | window. The event; console.log(e); } </script>Copy the code

Properties and methods of the event object

The difference between e.target and this

  • This is the element of the event binding (the element that binds the event handler).

  • E.target is the element that triggers the event.

Usually terget and this are the same, but when the event bubbles (the parent element has the same event, and clicking on the child element triggers the parent element's event handler), this refers to the parent element because it is the element object to which the event is bound. Target refers to the child element because it is the specific element object that triggered the event.Copy the code
<div>123</div> <script> var div = document.querySelector('div'); Div. AddEventListener ('click', function(e) {// e.target and this point to div console.log(e.target); console.log(this); }); </script>Copy the code

Events bubble under E.target and this

<ul> <li>abc</li> <li>abc</li> <li>abc</li> </ul> <script> var ul = document.querySelector('ul'); Ul.addeventlistener ('click', function(e) {this points to ul console.log(this); // ul // e.target the object that triggered the event we clicked on li e.target pointing to Li console.log(e.target); // li }); </script>Copy the code

7.7 Prevent default behavior

Some tags in the HTML have default behaviors. For example, after a tag is clicked, the page is redirected by default.

< a href = "http://www.baidu.com" > baidu < / a > < script > / / 2. Var a = document.querySelector('a'); a.addEventListener('click', function(e) { e.preventDefault(); }); A.onclick = function(e) {// e.preventdefault (); Methods e.p reventDefault (); // Ie678 returnValue property e.returnValue = false; // We can use return false to prevent default behavior. } </script>Copy the code

7.8 Preventing events from bubbling

The nature of the event bubble itself will bring both harm and good.

<div class="father"> <div class="son">son </div> </div> Son.addeventlistener ('click', function(e) {alert('son'); e.stopPropagation(); / / stop stop Propagation transmission window. Event. CancelBubble = true; // Cancel bubble}, false); var father = document.querySelector('.father'); AddEventListener ('click', function() {alert('father'); }, false); / / to the document registered click event document. The addEventListener (' click ', function () {alert (' document '); }) </script>Copy the code

Compatibility handling to prevent event bubbling

7.9 Event Delegation

Event delegation: To entrust something to someone else to deal with it. Event delegates are also called event proxies, or event delegates in jQuery.Copy the code

In plain English, you do not register events for child elements, register events for parent elements, and execute the processing code in the event of the parent element.

Proxy in js events:

The principle of event delegation

Register events for the parent element and use event bubbling. When the child element’s event is triggered, it will bubble to the parent element and then control the corresponding child element.

The role of event delegation

  • We only manipulated the DOM once, improving the performance of the program.

  • Dynamically newly created child elements also have events.

<ul> <li> Know you know, I should have a frame in hand! </li> <li> </li> </li> <li> </li> </li> <li> </li> </li> <li> </li> </li> </ul> <script> </li> </ul> </ul> Ul. AddEventListener (' click ', function (e) {/ / e. arget this can get us click on the object of e. arget. Style. The backgroundColor = 'pink'; }) </script>Copy the code

8. Dom manipulation

With respect to DOM manipulation, we focus on manipulation of elements. There are mainly create, add, delete, change, check, attribute operation, event operation.

8.1. To create

Increased 8.2.

8.3 delete

Change 8.4.

8.5. Check

8.6. Attribute operations

= = = = = = = = = = = = = = = = = = = to update the = = = = = = = = = = = = = = = = = = = = = = = = = = = =