Closure, deep copy and shallow copy in Practical Training JQuery

The essence of jQuery is JavaScript. If JavaScript can't do it, jQuery can do it

jQuery operates directly on documents

Now the more popular is: data driven

Data driven:

Database driver is a program developed by different database developers (such as Oracle, mysql, etc.) for a certain development language environment (such as Java) to realize unified database call. Its function is equivalent to a translator to translate the database call language in Java language into their own database language of various databases through this translation, Of course, this translation (database driven) is customized and developed by various developers for a unified interface

In addition:

The so-called "Data-Driven" is the "data cycle" of the internal operation of the enterprise. Through data analysis and value discovery, we can improve the core links such as customers, products, infrastructure and profit mode, form a unique competitive advantage, and finally realize the rapid operation of the whole enterprise and even the supply chain. Such enterprises are data-driven enterprises, which we call "data flywheel". Whether a "data flywheel" is formed within an enterprise depends on whether all links of enterprise operation are supported by data.
(1) Customer module: mainly "relationship data flywheel": the connection mode between enterprises and customers has changed fundamentally, the traditional channel providers and middlemen have been gradually weakened, and the direct connection of customers to brands has become the trend of future development; Crowd is communication, where there is an interface, marketing is needed, and the interface between products and consumers is the marketing point; Enterprises can use O2O
Of 23
Relationship data of multiple touchpoints for Omni channel management and omni media marketing.
(2) Product module: mainly "value data flywheel": the R & D and design of products are derived from the data fed back and participated by users; In the product value, the value of the information part is getting higher and higher. For example, the cost of Tesla machinery part is less than 30%, but the cost of the information part is very high; We must divide product design into standard products and non-standard products, lower the price of standard products, compete with competitors, increase the price of non-standard products and make profits.
(3) Infrastructure module: in the infrastructure module, it is mainly the "platform data flywheel": the platform of internal and external resources. The infrastructure used to be the enterprise's own production platform. In recent years, it can be its own, partner or even socialized; From flexible manufacturing to crowdsourcing and crowdfunding, and even logistics, it can be regarded as an enterprise's data resource platform.
(4) Profit model module:
The profit model has quietly changed: the flexibility of revenue mode and the de risking of transaction mode, charging to free, one transaction to multiple transactions, and paying directly to a third party, which means that consumers will no longer hesitate to buy things and have no worries about multiple transactions. Thus, the "profit model" of the enterprise is formed.


A function is bound with a reference to its surrounding state (lexical environment) (or the function is surrounded by a reference). Such a combination is a closure. That is, closures allow you to access the scope of its outer function in an inner function. In JavaScript, whenever a function is created, the closure is created at the same time as the function is created.

Syntax scope:

function init() {
    var name = "Mozilla"; // name It's a quilt init Created local variable
    function displayName() { // displayName() Is an internal function, a closure
        alert(name); // A variable declared in the parent function was used

init()   Created a local variable   name   And one named   displayName()   Function of. displayName()   Is defined in   init()   Internal functions in, and only in   init()   Available in the function body. Notice that displayname()   There is no local variable of its own. However, because it can access variables of external functions, so   displayName()   You can use parent functions   init()   Variables declared in   name  .

use This JSFiddle link After running the code,   displayName()   In function   alert()   The statement successfully displays the variable   name   The value of the variable declared in its parent function. This lexical scope example describes how the parser parses variable names when functions are nested. The term lexical means that the lexical scope determines where a variable is available based on the location of the declared variable in the source code. Nested functions can access variables declared outside their scope.

For details, please refer to: Closure - JavaScript | MDN (

Deep and shallow copies:

Deep copy and shallow copy are only for reference data types such as Object and Array  . Shallow copy only copies the pointer to an Object, not the Object itself. The old and new objects still share the same block of memory. But deep copy as like as two peas will create another Object that is exactly the same. New objects do not share memory with original objects, and new objects will not be changed to original objects.

Specific differences:

The most fundamental difference between deep copy and shallow copy is whether to really obtain the copied entity of an object rather than a reference.

Suppose B copies A. when modifying a, check whether B changes:

If B also changes, it means that it is a shallow copy, and the hand is short! (modify the same value in heap memory)

If B doesn't change, it means it's a deep copy and independent! (modify different values in heap memory)

Shallow copy only adds a pointer to the existing memory address,

Deep copy is to add a pointer and apply for a new memory, so that the increased pointer points to the new memory,

When using deep copy, the same memory will not be released when releasing memory because of the error of releasing the same memory when using shallow copy.

Shallow copy: it only points to the copied memory address. If the original address changes, the shallow copied object will change accordingly.

Deep copy: open up a new memory address in the computer to store the copied objects.

Shallow copy instance:

//This recursive method does not contain an array object
var obj = { a:1, arr: [2,3] };
var shallowObj = shallowCopy(obj);

function shallowCopy(src) {
var newobj = {};
for (var prop in src) {
if (src.hasOwnProperty(prop)) {
newobj[prop] = src[prop];
return newobj;

Because shallow copy only copies the attributes of the object, not recursively, and JavaScript storage objects are stored at addresses, shallow copy will cause Obj.arr and shallowObj.arr to point to the same memory address:


The result is:

shallowObj.arr[1] = 5;
console.log(obj.arr[1]); //5

Deep copy instance:

var obj = {
arr: [1,2],
nation : 'China',
var obj2 = {name:'Yang'};
obj2 = deepCopy(obj,obj2);
//Deep replication requires recursion to achieve deep replication
function deepCopy(o, c){
var c = c || {};
for(var i in o){
if(typeof o[i] === 'object'){
if(o[i].constructor === Array){
//This is an array
c[i] = [];
//This is the object
c[i] = {};
deepCopy(o[i], c[i]);
c[i] = o[i];
return c;

Deep copy is different. It not only copies each attribute of the original object one by one, but also recursively copies the objects contained in each attribute of the original object to the new object by using the method of deep copy. There will be no problem that the arr attribute of obj and shallowObj point to the same object.



  In this way, obj1 and obj2 have different memory addresses, and the changes of values on both sides will not affect each other.

For details, please refer to: Difference between deep copy and shallow copy - meat cutter - blog Garden (


Specific problem example: 53. The following code wants to cycle delay output result 0 1 2 3 4. Is the output result correct, such as

If the result is incorrect, please explain why and modify the code in the loop to output the correct result

for (var i = 0; i < 5; ++i) {
setTimeout(function () {
console.log(i + ' ');
}, 100);

The correct result cannot be output because the parameter function accepted by setTimeout in the loop accesses variable i through closure. javascript operation
The line environment is single thread. The function registered by setTimeout needs to wait for the thread to be idle before execution. At this time, the for loop has ended, i
The value is 5. The five timing outputs are all 5 modification methods: put setTimeout in the function immediate call expression and take the i value as
Parameters are passed to the wrap function to create a new closure

for (var i = 0; i < 5; ++i) {
(function (i) {
setTimeout(function () {
console.log(i + ' ');
}, 100);


// var Will produce a pile of things
    for (var i = 0; i < 5; i++) {
        // Calling at the same time when declaring. If () is not added, a syntax error will be reported 
        // (i) Formal parameters can be changed
        // (i) Argument
// Closures: Functions--Give something to a function as a closure

54. Write javascript deep clone function deepClone

function deepClone(obj) {
var _toString = Object.prototype.toString;
// null, undefined, non-object, function
if (!obj || typeof obj !== 'object') {
return obj;
// DOM Node
if (obj.nodeType && 'cloneNode' in obj) {
return obj.cloneNode(true);
// Date
if ( === '[object Date]') {
return new Date(obj.getTime());
closure-Method is also equivalent to executing the function itself
 This output is always 5 because settimeout It means direct output
 Equivalent to you passing it to i What is the value of the output
 // RegExp
if ( === '[object RegExp]') {
var flags = [];
if ( { flags.push('g'); }
if (obj.multiline) { flags.push('m'); }
if (obj.ignoreCase) { flags.push('i'); }
return new RegExp(obj.source, flags.join(''));
var result = Array.isArray(obj) ? [] :
obj.constructor ? new obj.constructor() : {};
for (var key in obj ) {
result[key] = deepClone(obj[key]);
return result;
function A() {
this.a = a;
var a = {
name: 'qiu',
birth: new Date(),
pattern: /qiu/gim,
container: document.body,
hobbys: ['book', new Date(), /aaa/gim, 111]
var c = new A();
var b = deepClone(c);
console.log(c.a === b.a);
console.log(c, b);


var stu1={
    name:"Zhang San",
        // quantity==count
// A full reference to a direct assignment object is equivalent to stu1 and stu2 Same value
// Reference relation  stu1 and stu2 The relationship is a reference type
// var stu2 = stu1;
// console.log(stu2);

// Light copy handle stu1 Value for stu2 This object
// Disadvantages of shallow copy: non reference type, pointing
// Deep copy is used to judge reference types, different, including arrays and objects
var stu2 = {}; =; =;
stu2.class = {}; =;
stu2.class.count = stu1.class.count;


Posted by Peuplarchie on Mon, 08 Nov 2021 00:57:18 -0800