JavaScript nanny tutorial – – Detailed analysis of key and difficult points

    • 1. JS function
    • 2. JS event
    • 3. The JavaScript object
    • 4. JavaScript prototype
    • 5. What is the difference between call and bind?
    • 6. Javascript Event Flow Model (interview focus)
    • 7. Shockproof and Throttling (interview selection)
    • What is the virtual DOM in JS? (Interview highlights)
    • 9. Write a new by hand to achieve the same function
    • 10. Get the value of the page URL parameter (common)
  • This article is to sort out some key points in JS, difficult points, as well as the knowledge points that are not easy to understand
  • This article is very detailed, in-depth explanation, package learning package will \

1. JS function

1.1 What is a Function?

  • A function (method) is a reusable block of code that is either event-driven or executed when it is called
  • Official documents have always seemed a little stiff. Here’s an example:

Functions can be thought of as functions (take a car, as shown below), and these can be thought of as methods

  • The brake
  • The gas pedal
  • honking
  • gear

  • Any one of these functions has a lot of parts to complete a task together, we just need to call (step on the brake, step on the accelerator, honk the horn, gear), the function will be implemented
  • The same is true of functions, which encapsulate operations that will only be performed if we call them

1.2 One of the simplest functions and triggering methods

<! DOCTYPE html><html>
    <head>
        <meta charset="utf-8">
        <title>My first method</title>
    </head>
    <body>
        <button onclick="myFunction()">Click trigger function</button>
        <script>
            // Must have the function keyword, and the name is usually named after the hump, starting with a lowercase letter
            function myFunction(){
                alert("Here's my function.");
            }
        </script>
    </body>
</html>
Copy the code

1.3 Functions with arguments (form takes arguments)

  • Parameter: a variable defined in a function (this time it has no value, it is just a proxy)
  • Argument: the argument (the actual value) passed in the runtime function call
  • In js, a method can be called without an argument, even if the parameter is defined
<! DOCTYPE html><html>
    <head>
        <meta charset="utf-8">
        <title>The form participates in the argument</title>
    </head>
    <body>
        <! -- Where 5 and 2 are arguments -->
        <button onclick="addNum(5, 2)">Calculate the value of 5 plus 2</button>
        <script>
            // Where num1 and num2 are the parameters
            function addNum(num1, num2){
                alert(num1 + num2)
            }
        </script>
    </body>
</html>
Copy the code

1.4 Function with a return value ———— return

function fn(a, b){
    return a*b;
}
// Call and assign a value to num
let num = fn(3.5);
console.log(num) / / get 15
Copy the code

1.5Js function built-in objects ———— Arguments

  • It’s created as soon as the function is created
  • It’s a class array (not really an array)
  • When a method is called, you get all the arguments that were passed in
  • I get as much as you pass
function fn(){
    console.log(arguments)
 }
 fn(1.2.3.4);
Copy the code



Classical use ———— to find the sum of a set of parameters

 function fn(){
    let sum = 0;
    for(let i = 0; i < arguments.length; i++){
        sum += arguments[i];
    }
    / / returns the sum
    return sum
 }
 let allSum = fn(1.2.3.4);
 console.log(allSum)    / / get 10
Copy the code

1.6 Variables in a function

  • Variables defined within a function are local variables
  • After the function runs, it is destroyed (garbage collected), so it is not accessible to outsiders
  • Variables should not have the same name as much as possible (local and global variables can be confused, leading to unexpected problems)
function fn() {
    // This is a local variable
    let a = 5;
    console.log(a)
}
fn();
console.log(a) // An error is reported here
Copy the code

1.7 Anonymous Functions (difficulty)

  • As the name implies, a function without a name
  • The following syntax must be used, or an error will be reported
(function (){
    // Because the anonymous function is not executed, the statement inside the anonymous function is not executed.
    console.log("666");
})
Copy the code

Anonymous self-executing functions (similar to the JS singleton pattern)

(function (){
    console.log("666"); // This will print 666}) ()Copy the code

2. JS event

  • An HTML event is something that happens to an HTML element.
  • JavaScript can trigger these events.
  • It can be regarded as some user operations, or some operations that the business needs to listen on

2.1 HTML event

  • The HTML page is loaded
  • When the HTML INPUT field changes
  • The HTML button is clicked

Common Event sorting

The event name instructions
onchange() HTML element changes (typically for form elements)
onclick () The user clicks on the HTML element
onmouseover() The user moves the mouse over an HTML element
onmouseout() The user moves the mouse over an HTML element
onkeydown() The user presses a keyboard key
onkeyup() The keyboard keys come up
onload() The browser has loaded the page

2.2 What do JavaScript events generally do?

  • Events are triggered when the page loads
  • Events are triggered when the page closes
  • The user clicks the button to perform the action
  • Verify the validity of user input
  • … (All operations of the user can be monitored)

2.3 Event Instances

<input id="test" type="button" value="Submit"/>
<script>
// Triggers when the page is loaded
window.onload = function(){
    let test = document.getElementById("test");   
    test.addEventListener("click",myfun2);   
    test.addEventListener("click",myfun1);
}
function myfun1(){  
    alert("Hello 1");
}
function myfun2(){ 
    alert("Hello 2");
}
</script>
Copy the code

3. The JavaScript object

In JS – everything is an object \

  • A string can also be an object
  • A date is an object
  • Mathematics and regular expressions are also objects
  • An array is an object
  • Functions can also be objects

3.1 Object Definition

  • An object is a container for variables
  • Write in key-value pairs (key name: key value)
  • Key-value pairs are called properties of an object
  • Loop objects are commonly usedfor in
// Object definition
let person = {
    firstName:"ouyang".lastName:"xiu".age:18
};

// Loop object
for(let key in person){
	console.log(key);	/ / key name
	console.log(person[key])	/ / key values
}
Copy the code

3.2 Analysis of classic dafang interview questions

Let obj = object.create (null) let obj = {}

  • What’s the difference between creating an Object by Object literals and creating an Object by object.create (null)?
  • At first, it was a bit confusing, because it was all about creating objects, so what difference could it make? Later, I tried it, and found it was quite interesting:
let obj = {};
let obj2 = Object.create(null);
console.log(obj);
console.log(obj2)
Copy the code
  • Console printing

  • At first glance, it doesn’t seem to make any difference, just a curly brace
  • However,It really makes a difference

  • Object.create(NULL) creates an Object that is pure, without any other elements
  • Another let creates an Object with _proto_. There are some methods and properties below. This is js’s prototype chain inheritance, which inherits the methods and properties of Object. That’s the difference.

So this difference leads to different usage scenarios

  • If an object’s inherited properties and methods are needed, use themlet obj = {};
  • If only one pure object is needed, use itObject.create(null)
  • For example, I just need to use the object to hold some data, and then loop out, improve the efficiency of the loop.
  • At this point, if the object has a prototype chain, it loops through its properties and methods
  • However, this is not necessary, we just want the elements in it, the former will affect the recycling efficiency \

4. JavaScript prototype

  • This property is function specific
  • Each function is added by default
  • Used to inherit properties and methods
// Create the constructor
function Person(name, age) {
    this.age = age;
    this.name= name;
    this.fn = function(){
        console.log(this.name)
    }
}
Copy the code
// Create an instance
let person1 = new Person("Xiao Ming".18);
let person2 = new Person("Little red".20);
person1.fn(); // Inherit the parent method
person2.fn();
console.log(person1)
console.log(person2)
Copy the code

The execution result

  • To add a new property, add the following in the constructor function:
function Person(name, age, sex) {
   // Sex is the new attribute
   this.sex = sex;
   this.age = age;
   this.name= name;
   this.fn = function(){
       console.log(this.name)
   }
}
Copy the code

4.1 the prototype inheritance

All JavaScript objects inherit properties and methods from a prototype:

  • Date objects inherit from date.prototype
  • Array objects inherit from array. prototype
  • The Person object inherits from person.prototype

All objects in JavaScript are instances of Object at the top of the prototype chain

  • A JavaScript object has a chain that points to a prototype object
  • When it attempts to access a property of an object, it searches not only for the object, but also for the object’s archetypes, and the archetypes of the archetypes of the object, working its way up until it finds a property with a matching name or reaches the end of the stereotype chain.
  • Date, Array, and Person objects inherit from object.prototype.

4.2 Adding Properties and Methods

function Person(name, age, sex) {
    // Sex is the new attribute
    this.sex = sex;
    this.age = age;
    this.name= name;
    this.fn = function(){
        console.log(this.name)
    }
}
Person.prototype.newVal = "I'm a new value added to the prototype.";
let person1 = new Person("Xiao Ming".18);

console.log(person1)
Copy the code
  • You can get it by inheritance

5. What is the difference between call and bind?

  • The difference between this and apply is a classic interview question
  • There are also native JS methods that are often used in projects.
  • One of the many pits in ES5

5.1 Start with this

  • This refers to = who called, to whom (this is wrong!!)
  • This always refers to the last object that called it (positive solution)

How to solve this pointing problem?

  1. Use the arrow function in ES6
  2. The function uses _this = this internally
  3. Use the apply, call, bind methods
  4. New instantiates an object

5.2 Talk about apply, call, bind

  • apply()
let obj = {
    name : "Xiao Ming".func1: function () {
        console.log(this.name)
    },
    func2: function () {
        setTimeout(  function () {
            this.func1()
        }.apply(name),1000); }}; obj.func2()/ / xiao Ming
Copy the code
  1. apply()Method calls a function with a specified value of this and an argument provided as an array (or array-like object),fun.apply(thisArg, [argsArray])
  2. ThisArg: The value of this specified when fun is run. The value specified for this is not necessarily the actual value of this when the function is executed. If this is the original value, it points to the autowrap object for that original value.
  3. ArgsArray: An array or array-like object whose array elements are passed as separate arguments to fun. If the parameter is null or undefined, no parameters need to be passed.
  • call()
let obj2 = {
    name : "Little red".func1: function () {
        console.log(this.name)
    },
    func2: function () {
        setTimeout(  function () {
            this.func1()
        }.call(name),1000); }}; obj2.func2()/ / the little red
Copy the code
  1. call()Call a function with a specified value of this and a list of arguments, fun.call(thisArg, arg1, arg2,…)
  2. ThisArg: The value of this specified when fun is run. The value specified for this is not necessarily the actual value of this when the function is executed. If this is the original value, it points to the autowrap object for that original value.
  3. Arg1, arg2,… : Several parameter lists
  • bind()
let obj3 = {
    name : "Pig".func1: function () {
        console.log(this.name)
    },
    func2: function () {
        setTimeout(  function () {
            this.func1()
        }.bind(name)(),1000); }}; obj3.func2()/ / the pig
Copy the code
  1. bind()Create a new function, when called, with its this keyword set to the value provided, and provide a given sequence of arguments at any time when the new function is called.
  2. Bind creates a new function that must be called manually.

5.3 the difference between

  • Apply and Call are similar, except for the parameters passed in.
  • The arguments that apply passes are arrays of arguments
  • Call passes in a list of parameters
  • The bind method creates a new function that, when called, sets the this keyword to the supplied value. We must call it manually

6. Javascript Event Flow Model (interview focus)

  • Event bubble: Events begin to be accepted by the most specific elements and then propagate progressively upward

  • Event capture: Events are received first by the least specific node and then progressively down to the most specific (as opposed to above)
  • DOM event flow: three phases: event capture, target phase, and event bubble

7. Shockproof and Throttling (interview selection)

7.1 Function stabilization

  • When an event is triggered continuously, it can only be triggered once in a period of time. Merge several operations into a single operation. For example, there is a racing channel, the car through the time of 5s, 5s after the finish line, the implementation of the award operation

  • Only one car is allowed in the lane for the 5s, and if the first car is still in the lane,Now the second car has come in, so destroy the first carWhen the second car enters, it will be timed for 5 seconds to collect the prize

Application Scenario (Data jitter)

let telInput = document.querySelector('input'); TelInput. AddEventListener (' input ', function (e) {/ / if every time a direct request, will cause performance issues / / data request let timeOut = null; if(timeOut){ clearTimeout(timeOut) }else{ timeOut = setTimeout(()=>{ $.ajax({}) },2000) } })Copy the code

7.2 Function Throttling

  • When events are continuously raised, the event handler is guaranteed to be called only once in a certain period of time. Throttling, as the name suggests, is to control inflow or outflow.
  • For example, when water comes out of a faucet, once the switch is turned on, the water will flow quickly, and what we need to do is to limit the flow

Application Scenario (Passenger Station problem)

  • Compare the whole event handler to a passenger station. If the bus arrived and left, there would be a traffic jam and the bus would be mostly empty
  • Because did not give time on the guest, the false busy situation is certainly not good, so how to deal with it?
  • Set a time interval, the time interval is allowed to execute only once, the passenger station bus set a time, the arrival point will leave
let throttle = function(func, delay) {let prev = Date.now();return function() {var context = this;var args = arguments;var now = Date.now();if(now-prev >= delay) {func.apply(context, args); prev =Date. Now (); }}}function demo() {//do something
    //ajax({})
    / /...
}        
box.addEventListener('touchmove', throttle(demo, 2000));
Copy the code

What is the virtual DOM in JS? (Interview highlights)

8.1 Why a Virtual DOM?

  • The document Object Model, or DOM, defines an interface that allows languages such as JavaScript to access and manipulate HTML documents
  • But this interface comes at a cost, in the form of a lot of very frequent DOM operations that slow down the page
  • The virtual DOM is designed to solve the performance problem of manipulating the DOM

8.2 What is a Virtual DOM? The upside?

  • It’s essentially a JS object
  • Abstract real nodes into JS objects (document structure tree)
  • Virtual nodes (VNodes) represent nodes in the DOM tree. When manipulation is required, calculations and operations can be performed in the memory of the virtual DOM rather than on the real DOM.
  • This is naturally faster than directly manipulating the DOM

9. Write a new by hand to achieve the same function

function Person(name) {
    this.name = name
    this.sayName= function () {
        console.log(I was `The ${this.name}! `)}}function myNew(that, ... args) {
    const obj = Object.create(null)
    obj.__proto__ = that.prototype
    constres = that.call(obj, ... args)return res instanceof Object ? res : obj
}
let person= myNew(Person, 'Ming')
person.sayWorld(); // I'm Xiao Ming
Copy the code

10. Get the value of the page URL parameter (common)

function getQueryString(name) { 
  var reg = new RegExp("(^ | &)" + name + "= (/ ^ & *) (& | $)"."i"); 
  var r = window.location.search.substr(1).match(reg); 
  if(r ! =null) return unescape(r[2]); 
  return null; 
} 
Copy the code

1. I hope this article will be helpful to you. If there are any mistakes, please point out

2. It is not easy to be original, please all guest officials to support a wave of small hands to make a fortune (attention, comment, like, collection) Thank you.