- This paper sorts out some key points, difficulties and knowledge points that are not easy to understand in JS
- This article is very detailed and in-depth explanation, including learning and meeting
1. JS function
1.1 what is a function?
- A function (method) is a reusable block of code that is event driven or executed when it is called - an official description
- I have always felt that the official documents are somewhat stiff. For example:
Functions can be regarded as functions (take a car as an example, as shown in the figure below), which can be seen as methods
- brake
- throttle
- whistle
- Gear
- Any one of these functions has the cooperation of many parts to complete a task together. We only need to call (step on the brake, step on the accelerator, honk and gear), and the function will be executed
- Function is the same. It encapsulates some operations, which will be executed only when we call it
1.2 the simplest function and trigger method
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>My first method</title> </head> <body> <button onclick="myFunction()">Click trigger function</button> <script> // There must be a function keyword, which is usually named after the hump, with the first letter in lowercase function myFunction(){ alert("This is my function"); } </script> </body> </html>
1.3 functions with parameters (formal and actual parameters)
- Formal parameter: the variable defined in the function (at this time, it has no value, but is a surrogate)
- Argument: the parameter (actual value) passed in during the function call at run time
- js, even if the formal parameter is defined in the method, no error will be reported if the actual parameter is not passed during the call
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Formal parameter and argument</title> </head> <body> <!-- Here 5 and 2 are arguments --> <button onclick="addNum(5, 2)">Calculation 5+2 Value of</button> <script> // num1 and num2 here are formal parameters function addNum(num1, num2){ alert(num1 + num2) } </script> </body> </html>
1.4 function with return value -- return
function fn(a, b){ return a*b; } // Call and assign value to num let num = fn(3, 5); console.log(num) // Get 15
1.5 built in object of JS function -- arguments
- It is available as soon as the function is created
- Is an array of classes (not a real array)
- When the method is called, you can get all the parameters passed in
- I can get as much as you pass
function fn(){ console.log(arguments) } fn(1, 2, 3, 4);
Classical application -- finding the sum of a group of parameters
function fn(){ let sum = 0; for(let i = 0; i < arguments.length; i++){ sum += arguments[i]; } // Return to sum return sum } let allSum = fn(1, 2, 3, 4); console.log(allSum) // Get 10
1.6 variables in functions
- The variables defined in the function are local variables
- After the function runs, it will be destroyed (garbage collection mechanism), so the outside world cannot access it
- Variables should avoid duplicate names as much as possible (local and global variables may be confused, resulting in some unexpected problems)
function fn() { // This is a local variable let a = 5; console.log(a) } fn(); console.log(a) // Error reported here, unable to access
1.7 anonymous function (difficulty)
- As the name suggests, it refers to a function without a name
- The following syntax must be used, otherwise an error will be reported
(function (){ //Since the anonymous function is not executed, the statement in the anonymous function body will not be executed. console.log("666"); })
Anonymous self executing function (similar to the singleton mode of JS)
(function (){ console.log("666"); // 666 will be printed here })()
2. JS event
- HTML events are things that happen on HTML elements.
- JavaScript can trigger these events.
- It can be regarded as some operations of the user, or some operations that the business needs to listen to
2.1 HTML events
- HTML page finished loading
- When the HTML input field changes
- HTML button clicked
Common event sorting
Event name | explain |
---|---|
onchange() | HTML element change (generally used for form elements) |
onclick () | The user clicks on the HTML element |
onmouseover() | The user moves the mouse over an HTML element |
onmouseout() | The user removes the mouse from an HTML element |
onkeydown() | The user presses the keyboard key |
onkeyup() | Keyboard keys pop up |
onload() | The browser has finished loading the page |
2.2 what are JavaScript events commonly used for?
- Event triggered when a page is loaded
- Event triggered when the page is closed
- The user clicks the button to execute the action
- Verify the legitimacy of user input
- ... (all operations of the user can be monitored)
2.3 event examples
<input id="test" type="button" value="Submit"/> <script> // Trigger after page loading 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>
3. JavaScript object
In JS - everything is an object
- A string can also be an object
- Date is an object
- Math and regular expressions are also objects
- An array is an object
- Functions can also be objects
- ...
3.1 object definition
- Objects are containers for variables
- It is written in the form of key value pair (key name: key value)
- Key value symmetry is the attribute of the object
- Circular objects are generally used for 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 value }
3.2 analysis of classic interview questions in large factories
let obj = Object. What is the difference between create (null) and let obj = {}?
- During the previous interview with Tencent, I asked this question: object literal creation object and object What's the difference between create (null) and creating objects?
- At first, I was a little confused. They all created objects. What can be the difference? Later, I tried it and found it quite interesting:
let obj = {}; let obj2 = Object.create(null); console.log(obj); console.log(obj2)
- Console printing
- At first glance, there seems to be no difference. They are all curly braces
- However, after expansion, it is quite different
- Object.create(null) creates a very pure object without any other elements
- Another let creates an Object with_ proto_ , there are some methods and properties below. This is the prototype chain inheritance of js, which inherits the methods and properties of Object. This is the difference.
Therefore, this difference leads to different usage scenarios
- If you need the inherited properties and methods of the object, use let obj = {};
- If you only need a pure object, use object create(null)
- For example, I only need to use objects to save some data, and then make cyclic access to improve the efficiency of the cycle.
- At this time, if the object has a prototype chain, it will cycle its properties and methods during the cycle
- However, this is not necessary. We just want the elements in it. The former will affect the cycle efficiency
4. JavaScript prototype
- This property is function specific
- Each function adds one by default
- Used to inherit properties and methods
// Create constructor function Person(name, age) { this.age = age; this.name= name; this.fn = function(){ console.log(this.name) } }
// Create instance let person1 = new Person("Xiao Ming", 18); let person2 = new Person("Xiao Hong", 20); person1.fn(); // Method of inheriting parent person2.fn(); console.log(person1) console.log(person2)
results of enforcement
- To add a new attribute, you need to add in the constructor function:
function Person(name, age, sex) { // sex is a new attribute this.sex = sex; this.age = age; this.name= name; this.fn = function(){ console.log(this.name) } }
4.1 prototype inheritance
All JavaScript objects inherit properties and methods from a prototype object:
- Date object from date Prototype inheritance
- Object from Array.array Prototype inheritance
- The Person object is from Person Prototype inheritance
All objects in JavaScript are instances of objects at the top of the prototype chain
- JavaScript objects have a chain that points to a prototype object
- When trying to access the properties of an object, it searches not only on the object, but also the prototype of the object and the prototype of the prototype of the object. It searches up layer by layer until it finds an attribute with matching name or reaches the end of the prototype chain (level by level search)
- Date object, Array object, and Person object from object Prototype inheritance.
4.2 adding attributes and methods
function Person(name, age, sex) { // sex is a new attribute this.sex = sex; this.age = age; this.name= name; this.fn = function(){ console.log(this.name) } } Person.prototype.newVal = "I am a new value added to the prototype"; let person1 = new Person("Xiao Ming", 18); console.log(person1)
- You can get it through inheritance
5. Differences between call, apply and bind (interview focus)
- The difference between this, apply, call and bind is a classic interview question
- At the same time, the native js method is often used in the project.
- It is also one of many pits in ES5
5.1 start with this
- This = who calls, who points (this is wrong!!!)
- this always points to the last object to call it (positive solution)
How to solve this pointing problem?
-
Use the arrow function in ES6
-
Function internal use_ this = this
-
Use the apply, call and bind methods
-
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
-
The apply() method calls a function that has a specified value of this and a parameter provided as an array (or an array like object), fun apply(thisArg, [argsArray])
-
thisArg: the value of this specified when the fun function runs. The specified value of this is not necessarily the real value of this when the function is executed. If it is the original value of this, it will point to the automatic wrapping object of the original value.
-
argsArray: an array or array like object in which the array elements will be passed to the fun function as separate parameters. If the parameter is null or undefined, it means that no parameters need to be passed in.
- call()
let obj2 = { name : "Xiao Hong", func1: function () { console.log(this.name) }, func2: function () { setTimeout( function () { this.func1() }.call(name),1000); } }; obj2.func2() // Xiao Hong
-
call() calls a function with a specified value of this and several parameter lists, fun call(thisArg, arg1, arg2, …)
-
thisArg: the value of this specified when the fun function runs. The specified value of this is not necessarily the real value of this when the function is executed. If it is the original value of this, it will point to the automatic wrapping object of the original value.
-
arg1, arg2,...: several parameter lists
- bind()
let obj3 = { name : "Little pig", func1: function () { console.log(this.name) }, func2: function () { setTimeout( function () { this.func1() }.bind(name)(),1000); } }; obj3.func2() // Little pig
-
bind() creates a new function. When called, set its this keyword to the provided value. When calling the new function, provide a given parameter sequence at any time.
-
bind creates a new function that must be called manually.
5.3 differences
- apply and call are basically similar. The only difference between them is that the parameters passed in are different.
- The parameter passed in by apply is an array containing multiple parameters
- The parameters passed in by call are several parameter lists
- The bind method will create a new function. When called, set its this keyword to the provided value, and we must call it manually
6. Event flow model of JavaScript (interview focus)
-
Event bubbling: the event is first accepted by the most specific element, and then propagated upward level by level
-
Event capture: events are first received by the least specific node, and then level down to the most specific (opposite to the above)
-
DOM event flow: three stages: event capture, target stage and event bubbling
7. Anti shake and throttling (interview selection)
7.1 function anti shake
- When the event is triggered continuously, it can only be triggered once in a period of time. Merge several operations into one operation. For example, there is a racing track. The time for the car to pass is 5s. After 5s, it will reach the end and receive the prize
- Only one racing car is allowed to be in the channel within 5s. If the first racing car is still in the channel and the second racing car has come in, destroy the first racing car and re count 5s from the second car to receive the prize
Application scenario (data jitter)
let telInput = document.querySelector('input'); telInput.addEventListener('input', function(e) { //If you send a request directly each time, it will lead to performance problems //Data request let timeOut = null; if(timeOut){ clearTimeout(timeOut) }else{ timeOut = setTimeout(()=>{ $.ajax({}) },2000) } })
7.2 function throttling
- When the event is triggered continuously, it is ensured that the event handler function is called only once within a certain period of time. Throttling, as the name suggests, controls inflow or outflow.
- For example, once the tap is turned on, the water will flow quickly. What we have to do is to limit the outflow
Application scenario (passenger station problem)
-
The whole event processor is compared to a passenger station. If the passenger bus leaves at the station, there will be traffic congestion on the road, and most of the cars are empty
-
Because there is no time for guests, the false busy situation must be bad, so how to deal with it?
-
Set a time interval, which can only be executed once. Set a time for the bus at the passenger station before it leaves at the time
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));
8. What is the virtual DOM in JS? (key points of interview)
8.1 why virtual dom?
- The document object model or DOM defines an interface that allows languages such as JavaScript to access and manipulate HTML documents
- However, this interface needs to pay a price. A large number of very frequent DOM operations will slow down the page
- The appearance of virtual DOM is to solve the performance problem of operating dom
8.2 what is virtual dom? What are the benefits?
- The essence is JS object
- Real nodes are abstracted into JS objects (document structure tree)
- A virtual node (VNode) represents a node in the DOM tree. When manipulation is needed, calculations and operations can be performed in the memory of the virtual DOM, rather than on the real dom.
- This is naturally faster than manipulating the dom directly
9. Write a new to achieve the same function
function Person(name) { this.name = name this.sayName= function () { console.log(`I am ${this.name}!`) } } function myNew(that, ...args) { const obj = Object.create(null) obj.__proto__ = that.prototype const res = that.call(obj, ...args) return res instanceof Object ? res : obj } let person= myNew(Person, 'Xiao Ming') person.sayWorld(); // I'm Xiao Ming
10. Get the value of 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; }
1. I hope this article can be helpful to you. If there are any errors, please point them out
2. It's not easy to be original. Please use your little hands to make a fortune to support a wave (attention, comment, praise and collection)
3. Thank you!