closure
Closures are functions that can read variables inside other functions. In javascript, for example, local variables can only be read by child functions inside a function, so closures can be understood as “functions defined inside a function.” In essence, closures are Bridges that connect the inside and outside of a function.
I heard from some seniors that closure is one of the key points in the interview, so I decided to write an article about closure to deepen my understanding of this aspect.
Closures, first of all, involve global variables and local variables. By default, global variables cannot access local variables, but local variables can access global variables.
Such as:
function fn(){
var a = 10;
function fun(){
var b = 20;
console.log('I am fun function')}console.log('I am fn function')
fun() // The fun function is valid only when called here
}
fn()
Copy the code
Here are some important things about closures (ColSure) :
1. When a function is created, it creates two objects: the function itself and the scope chain object.
2. When the function is called, an execution environment object (active object) is created, and the active object is put in the call variable of the current active object.
What are the disadvantages of global and local variables?
1. When a function is defined outside the body, every function can be modified, which will cause global pollution.
2. Defined in the body of a function, only the current function can be used, but cannot be used globally.
So, if you want to be reusable without polluting, use closures!!
A classic closure consists of three steps:
1. Inner functions are nested within outer functions
2. The inner function uses local variables of the outer function
3. Use the inner function as the return value of the outer function
How can closures be reused without polluting the world?
If you call a normal function, the called function will be released, but after a closure, there will be a variable defined to suspend them, so that they can not be released.
See the picture below:
In the diagram above, I created a classic closure, and drew a sketch, function in the process of execution, the function of the part is the stack, with an address to save it, so, when we call, is called its address, because the function in the process of creating not only creates the function itself, also can create a scope chain object, and into the stack, After the call, it will be released, prevent memory, but the closure function, the scope of the outer function chain objects refer to the scope of the inner function object, and the inner function scope chain object refers to the active object inside a function call, and the active object is as outer function return values, at this time, The scope chain object of the outer function is suspended by the fn function established outside, so a closure environment is formed. So that they don’t get released. In order to achieve repeated use, but will not pollute the overall role.
Here’s an example I wrote with closures, clicking on each li to get their subscripts.
for(vari = ; i < list.length; i++){ list[i].onclick = (function(index){
return function(){
console.log(index)
}
})(i)
}
Copy the code
inheritance
Subclasses share the attributes and methods of their parent class. Js inheritance is based on prototype implementation. In addition, before talking about inheritance, we need to review another concept, polymorphism: overwrite, overload.
In terms of inheritance, I just want to write about ES6 inheritance, commonly known as syntactic sugar.
class Animal{
constructor(name){
this.name = name;
}
say(){
alert("my name is " + this.name);
}
eat(food){
alert()this.name +"is eating"+food); }}// The following is the inherited code:
calss cat extends Animal{
constructor(name){
super(name); }}var tom = new cat("tom");
tom.say();
tom.eat("apple");
console.log(cat instanceof Animal);//true
console.log(cat instanceof Cat);//true
Copy the code
A sidebar: instanceof is used to check whether an object is an instanceof an object.
Case study :(drag implementation)
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.box {
width: 200px;
height: 200px;
background-color: red;
position: absolute;
}
</style>
</head>
<body>
<div class="box" id="box1">box1</div>
<div class="box" id="box2">box2</div>
Copy the code
Here is the javascript code:
<script> class Drag { constructor (selector) { this.box = document.querySelector(selector) this.bindEvents() } bindEvents () { this.box.onmousedown = (e) => { let disX = e.offsetX; let disY = e.offsetY; document.onmousemove = e => { let top = e.clientX - disX; let left = e.clientY - disY; this.move(left, Top)} document.onmouseup = function () {document.onmouseover = null} // Prevent default behavior to prevent dragging text e.preventDefault()}} move (left, top) { this.box.style.left = left + 'px' this.box.style.top = top + 'px' } } class LimitDrag extends Drag { constructor (selector) {super(selector)} move (left, top) {if (left < 0) left = 0 if (top < 0) top = 0 Box-style. Top = top + 'px'}} New Drag('#box1') new LimitDrag('#box2') </script>Copy the code
Class LimitDrag extends Drag When you write this line of code, you already inherit something from the parent class.
Execute function immediately
There are two common forms for executing functions immediately:
(function () {… }) ()
(function () {… } ())
One is an anonymous function wrapped in a parenthesis operator followed by a parenthesis operator, and the other is an anonymous function wrapped in a parenthesis operator followed by a parenthesis operator, and the whole thing is wrapped in a parenthesis operator, and these two are equivalent. To execute immediately, notice that the function body must be followed by parentheses (), and that the function body must be a function expression rather than a function declaration.
As you can see from the figure, in addition to using the () operator,! Operators such as, +, -, = all perform immediately. These operators convert an anonymous function or function declaration into a function expression, as shown in the following figure. The body of a function is the form of a function declaration.
2. Use the benefits of executing functions immediately
Creating a new function scope by defining an anonymous function is equivalent to creating a “private” namespace whose variables and methods do not pollute the global namespace. To access the global object, pass in the global object as a parameter