This is the 28th day of my participation in the Gwen Challenge in November. Check out the details: The last Gwen Challenge in 2021.”

preface

Before is busy with business development, the basic knowledge of front end to check what are used, rarely has time to sink down and their induction, summarizes the basis, sometimes, what use, feel worthy of pay attention to the thing, are also recorded in his note, also not timely, and then as time goes by, one record everything is at sixes and sevens, I haven’t done it yet. This time, write the basic series of the front end

I plan to chat in a relaxed, chatty tone. If I’m not good at writing, I’ll let you know

Quickly review

Above,

  1. Var, let, const
  2. Stereotype inheritance and Class inheritance

modular

There must be a reason to use a technology, so using modularity gives us the following benefits

  • Resolving naming Conflicts
  • Provide reusability
  • Improve code maintainability

Execute function immediately

In the early days, it was common to implement modularity using immediately executing functions, which solved naming conflicts and contaminated global scopes through function scopes

(function(globalVariable){ 
    globalVariable.test = function() {} 
    / /... Declaring variables and functions does not pollute the global scope
})(globalVariable)
Copy the code

AMD and CMD

Since these two implementations are rarely seen today, I won’t go into details about the features, just how they are used.

// AMD 
define(['./a'.'./b'].function(a, b) { 
    // The module can be used after loading
    a.do() 
    b.do() 
})

// CMD 
define(function(require.exports.module) { 
    // Load the module
    // You can write require anywhere in the function body for lazy loading
    var a = require('./a') 
    a.doSomething() 
})
Copy the code

CommonJS

CommonJS was first used in Node and is still widely used today, as you can see in Webpack, but module management in Node is now a bit different from CommonJS.

// a.js
module.exports = { a: 1 } 

// or
exports.a = 1

// b.js 
var module = require('./a.js') 
module.a // -> log 1
Copy the code

Since CommonJS will still be used, some of the problems will be resolved here

First talk about the require

var module = require('./a.js') 
module.a
// Execute the function immediately, so as not to pollute the global variable,
// The important thing is module, which is a variable unique to Node

module.exports = { a: 1 } 

// module basic implementation
var module = { 
    id: 'xxxx'.I must know how to find him
    exports: {} // exports is an empty object
 } 
 Exports and module.exports are used in the same way
 var exports = module.exports 
 var load = function (module) { 
     // Export things
     var a = 1 
     module.exports = a
     return module.exports
 }; 
 // Then when I require to find unique
 // id, and then wrap the thing to be used with the immediate execution function
Copy the code

Exports and module.exports are used similarly, but cannot be assigned directly to exports. Exports = module.exports var exports = module.exports indicates that exports and module.exports share the same address. However, assigning directly to exports will no longer refer to the same memory address, and this modification will not apply to module.exports.

ES Module

ES Module is a modular solution implemented natively and differs from CommonJS in the following ways

  • CommonJS supports dynamic import, which isrequire(${path}/xx.js)The latter is not currently supported, but there is a proposal
  • CommonJS is a synchronous import, because it is used on the server, the files are local, and the synchronous import does not have much impact if the main thread is blocked. While the latter is asynchronous import, because for the browser, need to download the file, if also adopted synchronous import will have a great impact on rendering
  • If the exported value changes, the imported value does not change, so if you want to update the value, you must import it again. However, the ES Module uses real-time binding. The import and export values point to the same memory address, so the imported value changes with the exported value
  • ES Module will compile torequire/exportsTo perform the
// Import the module API
import XXX from './a.js' 
import { XXX } from './a.js' 

// Export the module API
export function a() {} 
export default function() {}
Copy the code

Proxy

If you’ve been following the progress of Vue, you probably already know that in Vue3.0, the Object. DefineProperty will be replaced by a Proxy for data responsiveness. Proxy is a new feature in ES6 that allows you to use operations in custom objects.

let p = new Proxy(target, handler)
Copy the code

Target represents the object to which the agent is to be added. The handler uses custom operations in the object, such as custom set or get functions.

Next we implement a data responsiveness through Proxy

let onWatch = (obj, setBind, getLogger) = > { 
    let handler = { 
        get(target, property, receiver) { 
            getLogger(target, property) 
            return Reflect.get(target, property, receiver) 
        },
        set(target, property, value, receiver) { 
            setBind(value, property) 
            return Reflect.set(target, property, value) 
        }
    } 
    return new Proxy(obj, handler)
}

let obj = { a: 1 } 
let p = onWatch( obj, (v, property) = > { 
    console.log('Listens on properties${property}Change for${v}`)},(target, property) = > { 
        console.log(` '${property}'=${target[property]}`) 
    }
)

p.a = 2 // Listen for attribute A change
p.a // 'a' = 2
Copy the code

In the above code, we inserted our function logic into the original logic by customizing the set and get functions to notify when any property of the object is read or written.

Of course, this is a simple version of the reactive implementation. If we need to implement a reactive in Vue, we need to collect dependencies in GET and distribute updates in SET. The reason why Vue3.0 uses Proxy to replace the original API is that Proxy does not need to add proxies for each attribute recursively. In addition, some data updates cannot be monitored in the original implementation. However, Proxy can perfectly monitor data changes in any way. The only drawback may be that browser compatibility is not good.

map, filter, reduce

What a map does is it creates a new array, iterates through the old array, takes each element and does some transformation and puts it in the new array.

[1.2.3].map(v= > v + 1) // -> [2, 3, 4]
Copy the code

The map callback takes three parameters: the current index element, the index, and the original array

['1'.'2'.'3'].map(parseInt)
Copy the code
  • First iterationparseInt('1', 0) -> 1
  • Second round of traversalparseInt('2', 1) -> NaN
  • The third iterationparseInt('3', 2) -> NaN

Filter is also used to generate a new array and add elements that return true to the array while iterating through the array. We can use this function to remove unwanted elements

let array = [1.2.4.6] 
let newArray = array.filter(item= >item ! = =6) 
console.log(newArray) / / [1, 2, 4]
Copy the code

Like Map, filter’s callback takes three arguments and is equally useful.

Finally, let’s talk about reduce, which is the most difficult part to understand. Reduce can convert elements of an array to a value through a callback function.

If we wanted to implement a function that adds up all the elements of a function to get a value, we might write code like this

const arr = [1.2.3] 
let total = 0 
for (let i = 0; i < arr.length; i++) { 
    total += arr[i] 
}

console.log(total) / / 6
Copy the code

However, if we use Reduce, we can optimize the traversal portion of the code into one line of code

const arr = [1.2.3] 
const sum = arr.reduce((acc, current) = > acc + current, 0) 
console.log(sum)
Copy the code

For Reduce, which takes two parameters, a callback function and an initial value, let’s break down the reduce process in the code above

  • First, the initial value is zero0The value is passed in as the first argument when the first callback function is executed
  • The callback function takes four arguments: cumulative value, current element, current index, and original array
  • When a callback is executed, the current value and the initial value are added to produce the result1The result is passed in as the first argument when the callback is executed the second time
  • So when the callback is executed the second time, the added values are respectively1 和 2, and so on, the result is obtained after the cycle ends6

conclusion

  1. modular
  2. proxy
  3. map, filter, reduce

Ps: Dry words or more boring, and hard to impress, we are still in daily use, more experience