An article takes you through function expressions, recursion, closures, variables, this objects, module scopes in JavaScript

Author| Jeskson

Source|Dada Front End Bistro

How functions are defined:

The first is a function declaration; the second is a function expression.

Grammar:

function functionName(arg0, arg1, arg2) {
 // Function Body
}

In Firefox, Safari, Chrome, and Opera:

This property gives you access to the name specified by this function.

console.log(functionName.name); // 'functionName'

Function declaration:

One of its important features is that a function declaration is elevated, that is, the function declaration is read before the code is executed, and the function declaration can be placed after the statement calling it.

// Call function
dada();
// Function declaration
function dada() {
 console.log('dada');
}

With function expressions, there are many different forms of function expressions

var functionName = function(arg0, arg1, arg2){
 // Function Body
}

The above statement, expressed in words, creates a function and assigns it to a variable, which we call an anonymous function because there is no function name, there is no identifier after the keyword function, and the name value of the anonymous function gets an empty string.

Note that function expressions are the same as other expressions and must be assigned before use, otherwise:

// call
da();
var da = function() {
 console.log('dada');
}

The key to distinguishing a function declaration from a function expression is to promote the function

// Function expression
var dada;
if(name) {
 dada = function() {
  console.log('da1');
 };
}else{
 dada = function() {
  console.log('da2');
 };
}

Recursive function

What is a recursive function is a function that calls itself by name.

function da(num) {
 if(num < 5) {
  return 'da';
 }else {
  return num * da(num-2);
 }
}

closure

Closure is a function that can access variables in another function. Creating a closure is creating another function within one function.

JavaScript Closure

JavaScript variables can be local or global.Private variables can be used for closures.

Closure is a function that can read internal variables of other functions.

For example, in javascript, only subfunctions within a function can read local variables, so closures can be interpreted as "functions defined within a function".

In essence, closures are bridges that connect the interior and exterior of functions.

closure is an exact but difficult computer term.

Within Perl, closures are implemented as anonymous functions with the ability to continuously refer to literal variables that are outside the scope of the function.These external text variables magically preserve their values (deep links) when the closure function was initially defined.

Creation of closures in Javascript

function a(){
 var i=0;
  function b(){
  alert(++i);
  }
 return b;
}
var c=a();
c();

1. Function b is nested inside function a; 2. Function a returns function b.

The interviewer asked me: What is a closure and how do I answer it?

Simply put, it refers to a function that has access to variables in the scope of another function.

It consists of two parts: a function and the environment in which it was created.The environment consists of any local variable in the scope at the time the closure is created.

Memory leak

A closure references an entire variable object that contains a function, and if an HTML element is stored in the scope chain of the closure, that means it cannot be destroyed.It is necessary for us to actively destroy this element after we have finished working on it.

function da() {
 var element = document.getElementById('nameDa');
 var id = element.id;
 element.onclick = function() {
  console.log(id);
 };
 element = null;
}

Timer inside function

When a timer inside a function references a variable object of an external function, the variable object will not be destroyed.

(function() { 
 var da = 0;
 setInterval(function() {
  console.log(da++);
 },1000);
})();

The process of using closures

A closure refers to a value in an external function variable object and calls the closure outside the external function.

The sum function is defined as follows:

function sum(arr) {
    return arr.reduce(function (x, y) {
        return x + y;
    });
}

sum([1, 2, 3, 4, 5]); // 15

Functional representation:

function lazy_sum(arr) {
    var sum = function () {
        return arr.reduce(function (x, y) {
            return x + y;
        });
    }
    return sum;
}

var f = lazy_sum([1, 2, 3, 4, 5]); // function sum()

f(); // 15

Closure characteristics:

Make it possible to access the internal variables of the function externally;
Local variables reside in memory;
Global variables can be avoided. Prevent global variable pollution;
Causes memory leak (A block of memory space is occupied for a long time without being freed)

Each execution environment has an object representing a variable, a variable object, and a general scope chain contains two variable objects, a local active object and a global variable object. The essence of a scope chain is a pointer list to a variable object, which only references but does not actually contain a variable object.

When a variable is accessed in a function, a variable with the same name is searched from the scope chain. Generally, when the function is executed, the locally active object is destroyed and the global scope is saved in memory.

An internal function adds the active object of its external function to its scope chain.A closure carries the scope of its function, consuming more memory, and using closures more often can lead to excessive memory usage.

Function expressions can be programmed dynamically without naming. Function expressions do not need names. Function declarations require names. Function expressions without names are called anonymous functions. Recursive functions use arguments.callee to call themselves recursively.

The scope chain of a closure contains its own scope, including the scope and global scope of the function. Generally, the function will be destroyed after execution, but the function returns a closure whose scope will remain in memory until the closure does not exist.

The module mode is to create private variables and privileged methods for a single instance.A singleton is an object with only one instance. It is created by the literal amount of the object.

var da = {
 name: 'dada',
 eat: function() {
  // Code
 }
};

Private Establishment and Private Functions

var singleton = function(){ 
 //Private variables and private functions
 var privateVariable = 10; 
 function privateFunction(){ 
 return false; 
 }
 //Privileges/Public Methods and Properties
 return { 
 publicProperty: true, 
 publicMethod : function(){ 
 privateVariable++; 
 return privateFunction(); 
 } 
 }; 
}();
var application = function(){ 
 //Private variables and functions
 var components = new Array(); 
 //Initialization
 components.push(new BaseComponent()); 
 //public
 return { 
 getComponentCount : function(){ 
 return components.length; 
 }, 
 registerComponent : function(component){ 
 if (typeof component == "object"){ 
 components.push(component); 
 } 
 } 
 }; 
}();

var singleton = function(){ 
 //Private variables and private functions
 var privateVariable = 10; 
 function privateFunction(){ 
 return false; 
 } 
 //create object
 var object = new CustomType(); 
 //Add Privileges/Public Properties and Methods
 object.publicProperty = true; 
 object.publicMethod = function(){ 
 privateVariable++; 
 return privateFunction(); 
 }; 
 //Return this object
 return object; 
}();


var application = function(){ 
 //Private variables and functions
 var components = new Array(); 
 //Initialization
 components.push(new BaseComponent()); 
 //Create a local copy of the application
 var app = new BaseComponent(); 
 //Public interface
 app.getComponentCount = function(){ 
 return components.length; 
 }; 
 app.registerComponent = function(component){ 
 if (typeof component == "object"){ 
 components.push(component); 
 } 
 }; 
 return app; 
}();

Imitate Block-Level Scope

function outputNumbers(count){ 
 for (var i=0; i < count; i++){ 
 alert(i); 
 } 
 alert(i); //count
}
function outputNumbers(count){ 
 for (var i=0; i < count; i++){ 
 alert(i); 
 } 
 var i; //Redeclare Variables
 alert(i); //count
}

Closure contains the entire variable object

function createFunctions(){ 
 var result = new Array(); 
 for (var i=0; i < 10; i++){ 
 result[i] = function(){ 
 return i; 
 }; 
 } 
 return result; 
}
function createFunctions(){ 
 var result = new Array(); 
 for (var i=0; i < 10; i++){ 
 result[i] = function(num){ 
 return function(){ 
 return num; 
 }; 
 }(i);
 } 
 return result; 
}

this

This, in a global function, this is equivalent to window, and when a function is called as a method of an object, this is equivalent to that object.

var name = "The Window"; 
var object = { 
 name : "My Object", 
 getNameFunc : function(){ 
 return function(){ 
 return this.name; 
 }; 
 } 
}; 
alert(object.getNameFunc()()); 
//"The Window" (in non-strict mode)

Any variable defined in a function can be considered private because it cannot be accessed outside the function.

Private variables include the parameters of the function, local variables, and other functions defined within the function.

function add(num1, num2){ 
 var sum = num1 + num2; 
 return sum; 
}
function MyObject(){ 
 //Private variables and private functions
 var privateVariable = 10; 
 function privateFunction(){ 
 return false; 
 } 
 //privileged method
 this.publicMethod = function (){ 
 privateVariable++; 
 return privateFunction(); 
 }; 
}
function Person(name){ 
 this.getName = function(){ 
 return name; 
 }; 
 this.setName = function (value) { 
 name = value; 
 }; 
} 
var person = new Person("dada"); 
alert(person.getName()); //"dada" 
person.setName("da"); 
alert(person.getName()); //"da"

Static Private Variables

(function(){ 
 //Private variables and private functions
 var privateVariable = 10; 
 function privateFunction(){ 
 return false; 
 } 
 //Constructor
 MyObject = function(){ 
 }; 
 //Public/Privileged Method
 MyObject.prototype.publicMethod = function(){ 
 privateVariable++; 
 return privateFunction(); 
 }; 
})();

JavaScript this keyword

this represents a reference to the current object in an object-oriented language.

However, this is not fixed in JavaScript; it changes with the execution environment.

In a method, this represents the object to which the method belongs. If used alone, this represents a global object. In a function, this represents a global object. In a function, this is undefined in strict mode. In an event, this represents the element that receives the event. Similar call() and apply() methods can reference this to any object.

this always returns an object, simply the object where the property or method is "current".

In the code above this.property, this represents the object where the property property is currently located.

var obj = {
  foo: function () {}
};

var foo = obj.foo;

// how to write
obj.foo()

// Writing Two
foo()

Although obj.foo and foo point to the same function, the results may be different

var obj = {
  foo: function () { 
  console.log(this.bar) 
  },
  bar: 1
};

var foo = obj.foo;
var bar = 2;

obj.foo() // 1
foo() // 2

var obj = { foo:  5 };

The variable obj is an address (reference).If you want to read obj.foo later, the engine first gets the memory address from obj, then reads out the original object from that address and returns its foo property.

http://www.ruanyifeng.com/blog/2018/06/javascript-this.html

In the blog platform, there is still a long way to go in the future, and I also hope that you can support, criticize and correct more articles in the future, so that we can make progress and take the road together.

Thank you very much to the reader for seeing this. If this article is well written, feels like I have something to do with Dada, feels like I can keep on learning, feels like this person can make friends, asks for compliments, asks for attention, asks for sharing, really for a warm man

Very useful!!!

Don't forget to leave a footprint of your study [compliment + collection + comment]

Author Info:

[Author]: Jeskson Original Public Number: Dada Front End Bistro. Welfare: Public Number replies to the big gift package for self-study materials (share in groups, just say anything you want, see if I have one)! [Reprint instructions]: Please explain the source of reprinting, thank you for your cooperation!~

Big Front End Development, Locate Front End Development Technology Stack Blog, PHP Background Knowledge Point, web Full Stack Technology Field, Data Structure and Algorithms, Network Principles and other understandable presentations to small partners.Thank you for your support and love!!!

If there are inadequacies in this number (e.g. copyright or other issues), please contact us in time to make corrections, which will be dealt with at the first time.

Please compliment!Because your approval/encouragement is my greatest motivation to write!

Welcome to your attention Dada CSDN!

This is a quality, attitudinal blog

Keywords: Front-end Javascript Firefox PHP network

Added by Twister1004 on Mon, 30 Dec 2019 03:08:45 +0200