Attached is the learning path chart

JavaScript data type

Undefined, Null, Boolean, String, Number, Symbol, BigInt;

Object is a reference type, including Array, RegExp, Date, Math, and Function.

Data type detection

  • The first detection method: Typeof

typeof 1 // 'number'  
  
typeof '1' // 'string'  
  
typeof undefined // 'undefined'  
  
typeof true // 'boolean'  
  
typeof Symbol(a)// 'symbol'  
  
typeof null // 'object'  
  
typeof [] // 'object'  
  
typeof {} // 'object'  
  
typeof console // 'object'  
  
typeof console.log // 'function'  
Copy the code
  • The second test: Instanceof

When we create a new object, the new object is the object from which it inherits its prototype chain. By instanceof, we can determine whether this object is the object generated by the previous constructor, and thus basically determine the data type of this new object.

let Car = function() {}  
  
let benz = new Car();  
  
benz instanceof Car; // true  
  
  
let car = new String('maomin');  
  
car instanceof String; // true  
  
  
let str = 'haojie';  
  
str instanceof String; // false  
Copy the code
  • The third kind of detection: the Object. The prototype. ToString

ToString () is an Object prototype method that returns a string of the format “[Object Xxx]”, where Xxx is the type of the Object and the first letter must be capitalized. For Object objects, toString() returns “[Object Object]”; Other objects need to be called by call to return the correct type information.

Object.prototype.toString({})       // "[object Object]"  
  
Object.prototype.toString.call({})  // Same result as above, add call also ok
  
Object.prototype.toString.call(1)    // "[object Number]"  
  
Object.prototype.toString.call('1')  // "[object String]"  
  
Object.prototype.toString.call(true)  // "[object Boolean]"  
  
Object.prototype.toString.call(function(){})  // "[object Function]"  
  
Object.prototype.toString.call(null)   //"[object Null]"  
  
Object.prototype.toString.call(undefined) //"[object Undefined]"  
  
Object.prototype.toString.call(/123/g)    //"[object RegExp]"  
  
Object.prototype.toString.call(new Date()) //"[object Date]"  
  
Object.prototype.toString.call([])       //"[object Array]"  
  
Object.prototype.toString.call(document)  //"[object HTMLDocument]"  
  
Object.prototype.toString.call(window)   //"[object Window]"  
Copy the code

Implement a data type detection method

function getType(obj){  
  
  let type  = typeof obj;  
  
  if(type ! = ="object") {    // Check typeof first, if it is a basic data type, return directly
  
    return type;  
  
  }  
  
  // If typeof returns object, regex returns result
  
  return Object.prototype.toString.call(obj).replace(/^\[object (\S+)\]$/.'$1');  // Note that there is a space between the re
  
}  
  
/* Code validation, need to pay attention to case, which is typeof judgment, which is toString judgment? Think about the next * /  
  
getType([])     // "Array" typeof [] is object, so toString is returned
  
getType('123')  // "string" typeof returns directly
  
getType(window) // "Window" toString returns
  
getType(null)   Typeof Null is object and toString is required
  
getType(undefined)   // "undefined" typeof returns directly
  
getType()            // "undefined" typeof returns directly
  
getType(function(){}) // "function" typeof can determine, so the first letter is lowercase
  
getType(/123/g)      / / "RegExp" toString returns
Copy the code

String manipulation methods:

1. charAt()

The charAt() method can be used to get a string at a specified position, with index being the string index value starting from 0 to String.leng -1, or returning an empty string if it is not in the range.

let str = 'abcde';
console.log(str.charAt(2));     / / return c
console.log(str.charAt(8));     // Returns an empty string
Copy the code

2. charCodeAt()

The charCodeAt() method returns the Unicode encoding for the character at the specified position. The charCodeAt() method is similar to the charAt() method in that it takes an index value as an argument, except that the former returns the encoding of the character at the specified position, while the latter returns a character substring.

let str = 'abcde';
console.log(str.charCodeAt(0));     / / back to 97
Copy the code

3. fromCharCode()

FromCharCode () can accept one or more Unicode values and then return a string. In addition, this method is static on a String, where each character in the String is specified by a separate numeric Unicode encoding.

String.fromCharCode(97.98.99.100.101)   / / return abcde
Copy the code

4. indexOf()

IndexOf (SearchValue, Fromindex) is used to retrieve the first occurrence of a specified string value in a string. It can take two arguments, searchValue for the substring to look for, fromindex for the start of the search, or, if omitted, to retrieve it from.

let str = 'abcdeabcde';
console.log(str.indexOf('a'));  / / returns 0
console.log(str.indexOf('a'.3));   / / return 5
console.log(str.indexOf('bc')); / / returns 1
Copy the code

5. lastIndexOf()

LastIndexOf () has a similar syntax to indexOf() in that it returns the last occurrence of a specified substring value, retrieved from back to front.

let str = 'abcdeabcde';
console.log(str.lastIndexOf('a'));  / / return 5
console.log(str.lastIndexOf('a'.3));   // returns 0 from index 3 forward
console.log(str.lastIndexOf('bc')); / / return 6
Copy the code

6. search()

stringObject.search(substr)

stringObject.search(regexp)

The search() method is used to retrieve a specified substring in a string, or to retrieve a substring that matches a regular expression. It returns the starting position of the first matched substring, or -1 if there is none.

let str = 'abcDEF';
console.log(str.search('c'));   / / return 2
console.log(str.search('d'));   / / return 1
console.log(str.search(/d/i));  / / return 3
Copy the code

7. match()

stringObject.match(substr)

stringObject.match(regexp)

The match() method retrieves a specified value within a string or finds a match for one or more regular expressions.

If the argument is passed a substring or a regular expression that does not perform a global match, the match() method performs a match from the starting position and returns NULL if no match is found. Otherwise, an array is returned that contains the matching text in its 0th element, along with two object attributes, index and input, representing the starting character index of the matching text and a reference to stringObject (the original string).

let str = '1a2b3c4d5e';
console.log(str.match('h'));    / / returns null
console.log(str.match('b'));    // Return ["b", index: 3, INPUT: "1a2b3C4d5e "]
console.log(str.match(/b/));    // Return ["b", index: 3, INPUT: "1a2b3C4d5e "]
Copy the code

If the argument is passed a regular expression with a global match, match() matches multiple times from the starting position until the end. If no match is found, null is returned. Otherwise, an array is returned with all the substrings that meet the criteria, and no index or input attributes.

let str = '1a2b3c4d5e';
console.log(str.match(/h/g));   / / returns null
console.log(str.match(/\d/g));  Return ["1", "2", "3", "4", "5"]
Copy the code

8. substring()

stringObject.substring(start,end)

Substring () is the most commonly used string interception method. It takes two arguments (which cannot be negative), the start and end positions to intercept, and returns a new string containing all characters from start to end-1. If the end parameter is omitted, it indicates that the start position is truncated until the end.

let str = 'abcdefg';
console.log(str.substring(1.4));   / / returns the BCD
console.log(str.substring(1));  / / return bcdefg
console.log(str.substring(-1)); // return abcdefg, which is treated as 0 when passed negative values
Copy the code

9. substring()

stringObject.slice(start,end)

The slice() method is very similar to the Substring () method in that it takes two arguments corresponding to the start and end positions, respectively. The difference is that the argument in slice() can be negative, and if it is negative, it specifies the position from the end of the string. That is, -1 is the last character of the string.

let str = 'abcdefg';
console.log(str.slice(1.4));   / / returns the BCD
console.log(str.slice(-3, -1)); / / returns the ef
console.log(str.slice(1, -1));  / / return bcdef
console.log(str.slice(-1, -3)); // Returns an empty string, or if there is a problem with the passed argument
Copy the code

10. substr()

stringObject.substr(start,length)

The substr() method extracts a specified number of characters from the start subscript in the string. The return value is a string containing the length of characters starting from stringObject’s start (including the character to which start refers). If length is not specified, the string returned contains characters from start to the end of stringObject. In addition, if start is negative, it is calculated from the end of the string.

var str = 'abcdefg';
console.log(str.substr(1.3))   / / returns the BCD
console.log(str.substr(2))  / / return cdefg
console.log(str.substr(-2.4))  // return fg, if the target length is large, the actual length shall be taken as the criterion
Copy the code

11. replace()

stringObject.replace(regexp/substr,replacement)

The replace() method is used for string substitution, which takes two arguments, the substring to be replaced (which can be a re) and the text to be replaced. If the first argument is passed in a substring or regular expression without a global match, the replace() method makes a single substitution (that is, the first one) and returns the resulting string after a single substitution.

let str = 'abcdeabcde';
console.log(str.replace('a'.'A')); / / return Abcdeabcde
console.log(str.replace(/a/.'A')); / / return Abcdeabcde
Copy the code

If the first argument is passed in a globally matched regular expression, replace() will replace the qualifying substring multiple times and return the resulting string with multiple substitutions.

var str = 'abcdeabcdeABCDE';
console.log(str.replace(/a/g.'A'));    / / return AbcdeAbcdeABCDE
console.log(str.replace(/a/gi.'$'));   / / return the $$$bcde bcde bcde
Copy the code

12. split()

stringObject.split(separator,howmany)

The split() method splits a string into an array of strings. Separator, the first argument, indicates the split position (the reference), and howmany, the second argument, indicates the maximum allowable length of the returned array (normally not set).

let str = 'a|b|c|d|e';
console.log(str.split('|'));    // return ["a", "b", "c", "d", "e"]
console.log(str.split('|'.3)); // return ["a", "b", "c"]
console.log(str.split(' ')); / / return [" a ", "|", "b", "|", "c", "|", "d", "|", "e"]
Copy the code

You can also use the re for segmentation

let str = 'a1b2c3d4e';
console.log(str.split(/\d/)); // return ["a", "b", "c", "d", "e"]
Copy the code

13. ToLowerCase () and toUpperCase ()

stringObject.toLowerCase() stringObject.toUpperCase()

The toLowerCase() method converts uppercase letters in a string toLowerCase letters, and the toUpperCase() method converts lowercase letters in a string toUpperCase letters.

let str = 'JavaScript';
console.log(str.toLowerCase()); / / return javascript
console.log(str.toUpperCase()); / / return JAVASCRIPT
Copy the code

Array manipulation methods:

1. ES6 Array.of()

The array.of () method creates a new Array instance with a variable number of arguments, regardless of the number or type of arguments.

The difference between array.of () and Array constructors is that they handle integer arguments: array.of (7) creates an Array with a single element of 7, while Array(7) creates an empty Array of length 7 (note: This is an array with seven empty Spaces, not seven undefined ones.

Array.of(7);       / / [7]
Array.of(1.2.3); / / [1, 2, 3]

Array(7);          // [,,,,,,]
Array(1.2.3);    / / [1, 2, 3]
Copy the code

2. ES6 Array.from()

The array.from () method creates a new, shallow-copy Array instance from an array-like or iterable.

Array.from('foo') // ['f', 'o', 'o']

Array.from([1.2.3].x= > x + x) / / (2, 4, 6]
Copy the code

3. ES6 find()

The find() method returns the value of the first element in the array that satisfies the provided test function. Otherwise return undefined.

const array1 = [5.12.8.130.44];

const found = array1.find(element= > element > 10);

console.log(found); // expected output: 12

Copy the code

4. ES6 findIndex()

The findIndex() method returns the index of the first element in the array that satisfies the provided test function. Returns -1 if no corresponding element is found.

const array1 = [5.12.8.130.44];

const isLargeNumber = (element) = > element > 13;

console.log(array1.findIndex(isLargeNumber)); // expected output: 3
Copy the code

5. ES6 fill()

The fill() method fills all elements of an array from the start index to the end index with a fixed value. Does not include terminating indexes.

const array1 = [1.2.3.4];

// fill with 0 from position 2 until position 4
console.log(array1.fill(0.2.4));
// expected output: [1, 2, 0, 0]

// fill with 5 from position 1
console.log(array1.fill(5.1));
// expected output: [1, 5, 5, 5]

console.log(array1.fill(6));
// expected output: [6, 6, 6, 6]
Copy the code

6. ES6 includes()

The includes() method is used to determine whether an array contains a specified value, returning true if it does and false otherwise.

const array1 = [1.2.3];

console.log(array1.includes(2)); // expected output: true

const pets = ['cat'.'dog'.'bat'];

console.log(pets.includes('cat')); // expected output: true

console.log(pets.includes('at')); // expected output: false
Copy the code

7. concat()

The concat() method is used to join two or more arrays. This method does not alter the existing array and only returns a copy of the concatenated array.

let arr1 = [1.2.3];
let arr2 = [4.5];
let arr3 = arr1.concat(arr2)
console.log(arr1) / / [1, 2, 3]
console.log(arr3) // [1, 2, 3, 4, 5]
Copy the code

8. join()

The join() method is used to put all the elements of an array into a single string. Elements are delimited by the specified delimiter. By default, the array is delimited with the ‘,’ sign and does not change the original array.

let arr = [2.3.4];
console.log(arr.join()); / / 2, 3, 4
Copy the code

9. push()

The push() method adds one or more elements to the end of the array and returns a new length. Add at the end, returns the length, changes the array.

const animals = ['pigs'.'goats'.'sheep'];

const count = animals.push('cows');
console.log(count);
// expected output: 4
console.log(animals);
// expected output: Array ["pigs", "goats", "sheep", "cows"]

animals.push('chickens'.'cats'.'dogs');
console.log(animals);
// expected output: Array ["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]
Copy the code

10. pop()

The pop() method removes and returns the last element of the array. Returns the last element that changes the array.

const plants = ['broccoli'.'cauliflower'.'cabbage'.'kale'.'tomato'];

console.log(plants.pop());
// expected output: "tomato"

console.log(plants);
// expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"]

plants.pop();

console.log(plants);
// expected output: Array ["broccoli", "cauliflower", "cabbage"]
Copy the code

11. shift()

The shift() method removes the first element from an array and returns the value of the first element. Returns the first element, changing the array.

const array1 = [1.2.3];

const firstElement = array1.shift();

console.log(array1);
// expected output: Array [2, 3]

console.log(firstElement);
// expected output: 1

Copy the code

12. unshift()

The unshift() method adds one or more elements to the beginning of the array and returns the new length. Returns the new length, changing the original array.

const array1 = [1.2.3];

console.log(array1.unshift(4.5));
// expected output: 5

console.log(array1);
// expected output: Array [4, 5, 1, 2, 3]
Copy the code

13. slice()

Returns a new array containing elements from the arrayObject from start to end (excluding the element). Returns the selected element. This method does not modify the array.

const animals = ['ant'.'bison'.'camel'.'duck'.'elephant'];

console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]

console.log(animals.slice(2.4));
// expected output: Array ["camel", "duck"]

console.log(animals.slice(1.5));
// expected output: Array ["bison", "camel", "duck", "elephant"]
Copy the code

14. splice()

The splice() method removes zero or more elements starting at index and replaces those deleted elements with one or more values declared in the argument list. If an element is deleted from an arrayObject, an array containing the deleted element is returned. The splice() method modifies the array directly.

const months = ['Jan'.'March'.'April'.'June'];
months.splice(1.0.'Feb');
// inserts at index 1
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "June"]

months.splice(4.1.'May');
// replaces 1 element at index 4
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "May"]

Copy the code

15. sort()

Sort by Unicode code position, ascending by default

const months = ['March'.'Jan'.'Feb'.'Dec'];
months.sort();
console.log(months);
// expected output: Array ["Dec", "Feb", "Jan", "March"]

const array1 = [1.30.4.21.100000];
array1.sort();
console.log(array1);
// expected output: Array [1, 100000, 21, 30, 4]

Copy the code

16. reverse()

The reverse() method is used to reverse the order of elements in an array. It returns the array upside down, changing the original array.

const array1 = ['one'.'two'.'three'];
console.log('array1:', array1);
// expected output: "array1:" Array ["one", "two", "three"]

const reversed = array1.reverse();
console.log('reversed:', reversed);
// expected output: "reversed:" Array ["three", "two", "one"]

// Careful: reverse is destructive -- it changes the original array.
console.log('array1:', array1);
// expected output: "array1:" Array ["three", "two", "one"]

Copy the code

17. every()

Returns true if the given function is run on each item of the array and returns true on each item

const isBelowThreshold = (currentValue) = > currentValue < 40;

const array1 = [1.30.39.29.10.13];

console.log(array1.every(isBelowThreshold));
// expected output: true
Copy the code

18. some()

Returns true if the given function is run on each item of the array and returns true on any of the items

const array = [1.2.3.4.5];

// checks whether an element is even
const even = (element) = > element % 2= = =0;

console.log(array.some(even));
// expected output: true
Copy the code

19. filter()

The given function is run on each item of the array, returning an array of items whose result is true

const words = ['spray'.'limit'.'elite'.'exuberant'.'destruction'.'present'];

const result = words.filter(word= > word.length > 6);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

Copy the code

20. map()

The given function is run on each item of the array, returning the result of each function call to form a new array

const array1 = [1.4.9.16];

// pass a function to map
const map1 = array1.map(x= > x * 2);

console.log(map1);
// expected output: Array [2, 8, 18, 32]

Copy the code

21. forEach()

ForEach array traversal

const array1 = ['a'.'b'.'c'];

array1.forEach(element= > console.log(element));

// expected output: "a"
// expected output: "b"
// expected output: "c"

Copy the code

Object operation methods:

1. Check whether the object is empty

  • Use ES6’s object.keys () method

let data = {}
let arr = Object.keys(data)
console.log(arr.length) / / 0
console.log(arr) / / []
Copy the code
  • Convert to a string for comparison

let data = {};
let flag = (JSON.stringify(data) == "{}");
Copy the code
  • For in loop judgment

let data = {};

let a = function (){

  for(var key in data) {
    return false;
  }
  return true;

}

a(); //true
Copy the code
  • Jquery isEmptyObject method

var data = {};
var a = $.isEmptyObject(data);
console.log(a); //true
Copy the code

2. Delete an attribute of the object

delete

let a = {a : 1.b: 2};
delete a.b;
console.log(a);  //{a: 1}
Copy the code

3. Add object properties

var a = {a: 1};
a.b = 2;
console.log(a); // {a: 1,b: 2}
Copy the code

4. Shallow copy

When an object is copied to another object data, as long as an object of data changes to another object will be changed Because shallow copy copy reference address, (must be in the object is multilayer can copy, single copy is numerical, multilayer instructions set inside the object, so copy the address.)

  • Method 1 (ES6 method) :

 var obj = {a: {name:"kaiqin".age:19}};
 var obj1 = Object.assign({},obj);
 obj1.a.name="wang"
 console.log(obj1) // Name has been changed
 console.log(obj) // Name has been changed
Copy the code
  • Method two: Use a for in loop to iterate over each attribute and assign them to the new object. The object must be in a multi-tier state to implement shallow copy

var obj = { a: {name:"kaiqin".age:19}};var obj2 = {a:1.b:2.c:3};
/ / multi-layer
function copy(obj){
      var newObj = {};
      for(var key in obj){
            newObj[key] = obj[key];
       }
return newObj;
}
/ / single
var obj1 = copy(obj);
obj1.a.name="wang"
console.log(obj1)
console.log(obj)
Copy the code

5. Deep copy

When one object copies the data of another object, changes to the data of one object do not affect the data of the other object because Deep Cobb copies the data of the object, not the address

  • Method 1: The object is a single layer

Object.assign()

var obj = {a:1.b:2.c:3}
var obj1 = Object.assign({},obj);
obj1.a = 30;
console.log(obj1,obj)
Copy the code
  • Parse (json.stringify ())

Parse () converts an object into a JSON string using json.stringify, and parses the string into an object using json.parse (). As you go, new objects are created, and the object opens up a new stack for deep copy.

let arr = [1.2, {name:'kobe'}]
let newArr = JSON.parse(JSON.stringify(arr))
arr[2].name = 'jodan'
console.log(arr)
console.log(newArr)
Copy the code

Anti-vibration throttling:

If a task is triggered frequently, the task is executed only when the task triggering interval exceeds the specified interval.

Specific example: there is an input box, after the input will call the interface, get the association word. However, because it is not good to call the interface frequently, we use the anti-shake function in the code, and only after a period of time after the user input, the interface will be called and associative words will appear.

function debounce(fn, wait) {
    var timeout = null;
    return function() {
        if(timeout ! = =null) 
                clearTimeout(timeout);
        timeout = setTimeout(fn, wait); }}// handle the function
function handle() {
    console.log(Math.random()); 
}
// Scroll events
window.addEventListener('scroll', debounce(handle, 1000));

Copy the code

Throttling: Only one task will be executed at a specified time interval.

Example:

1. Lazy load to listen to calculate the scrollbar position, use throttling according to a certain frequency of time.

2. The user clicks the submit button. Assuming we know the approximate return time of the interface, we use throttling and only allow one click within a certain period of time.

var throttle = function(func, delay) {
    var 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 handle() {
    console.log(Math.random());
}
window.addEventListener('scroll', throttle(handle, 1000));
Copy the code

Front-end agile development processes

markdown

Markdown is a mark-like language with a plain text syntax format. Readme files are usually used for formatting

apipost

It can be used to request interfaces and generate documents.

Potholes at work

  1. In the process of marker generation of Gaode Map, if a certain coordinate does not exist in the list, the whole marker generation will fail. The idea to solve the problem is to judge whether the coordinate exists before generating marker, and then jump out of execution and carry out the next cycle if it does not.
try {
        list.forEach((marker, i) = > {
          let longitude = marker.longitude;
          let latitude = marker.latitude;
          if(! longitude || ! latitude) {throw new Error("LoopTerminates");
          }
          var amarker = new AMap.Marker({
            map: map,
            clickable: true.icon: "healthImg/addressIcon.png".position: [longitude, latitude],
            draggable: true}); amarker.setLabel({content: `<div style="color:blue">The ${this.map_index == 1 ? marker.name : marker.businessName
            }</div>`.direction: "bottom"}); }); }catch (e) {
        if(e.message ! = ="LoopTerminates") throw e;
      }
Copy the code
  1. When Echarts generates legends, if the example diagrams cannot be displayed, data in Legend and name in Series need to correspond one by one.

  1. Flex layout creates gap solutions

Flex layout elements will have default gaps, workaround

align-content: flex-start

Specific parameters are as follows:

The value can be: flex-start: aligns with the starting point of the crossed axis. Flex-end: aligns with the end of the cross axis. Center: aligns with the midpoint of the intersecting axis. Stretch (default) : Axis takes up the entire cross axis. Space-between: aligned with both ends of the intersecting axes, with evenly distributed spacing between axes. Space-around: The spacing on both sides of each axis is equal. Therefore, the spacing between axes is twice as large as the spacing between axes and borders.

legend.data = ["Inpatient care"."Home care"]
series[0].name = "Inpatient care"
series[1].name = "Home care"
Copy the code

Advanced knowledge of CSS:

1. How to reference CSS variables globally in VUE

Under normal circumstances, SCSS or LESS will be used in projects. Here, I choose TO use SCSS for illustration. We need to download an SCSS dependency.

npm install sass-loader sass --save
Copy the code

Then configure it in vue.config.js, where I list the files

const path = require('path')

function resolve(dir) {
  return path.join(__dirname, dir)
}

module.exports = {
  css: {
        loaderOptions: {
                scss: {
                        prependData: `@import "@/style/gobal.scss"; ` // This corresponds to the file directory}}}Copy the code

This way we can use variables in the @/style/gobal. SCSS directory for each vue component.

2. How to reference CSS styles globally in VUE

We all know that if we don’t style our browsers, we’ll find that we write things that look different in different browsers. These styles do not need to be used in vUE components. We just need to configure these styles globally. It’s very simple. We write styles directly in the Style directory.

The contents of this folder, when packaged, will be automatically loaded in index.html, so we can configure some initialization styles here.

3. Px to REM automatic adaptation

When doing mobile terminal projects, we need to adjust the width and height of our project elements according to different devices. If we use PX, the deviation will be caused by the different sizes of mobile phones. Let’s use REM for 100% control.

Install dependencies

npm install postcss-plugin-px2rem -D
npm install lib-flexible
Copy the code

Vue.config.js configuration plug-in

module.exports = {
  css: {
        loaderOptions: {
                 postcss: {
                        plugins: [
                                require('postcss-plugin-px2rem') ({rootValue: 75.exclude: /(node_module)/,
                                        minPixelValue: 3.selectorBlackList: ['van']})]}}Copy the code

The main js configuration

import 'lib-flexible/flexible.js'
Copy the code

Then when you use PX in your project, it automatically converts to REM

This, call, apply, bind

The new binding

When a function is called as a constructor using new, this binds to an instance of the newly created constructor.

function Foo() {
    console.log(this)}var bar = new Foo()       // Output: Foo instance, this is bar
Copy the code

Explicitly bound

With call, apply, and bind we can modify the function binding’s this to be the object we specify. We can explicitly bind this with the first argument to these methods.

function foo(name, price) {
    this.name = name
    this.price = price
}

function Food(category, name, price) {
    foo.call(this, name, price)       // Call
    // foo. Apply (this, [name, price]) // apply
    this.category = category
}

new Food('food'.'hamburger'.'$5')

/ / the browser output: {name: "hamburger," price: "five dollars," category: "food"}
// Here the reference to this becomes the constructor, so these attributes are all on new Food()
Copy the code

The difference between Call and apply is that the Call method accepts a list of parameters, while the apply method accepts an array of parameters.

func.call(thisArg, arg1, arg2, …) / / call usage

func.apply(thisArg, [arg1, arg2, …] ) // apply

The bind method, on the other hand, sets this to the given value, returns a new function, and calls the new function with the given argument list as the first items of the original function’s argument sequence.

Func. Bind (thisArg [, arg1, arg2 [[,…]]]] / / bind usage

var food = {
    name: 'hamburger'.price: '$5'.getPrice: function(place) {
        console.log(place + this.price)
    }
}

food.getPrice('KFC ')   // Browser output: "KFC 5 yuan"

var getPrice1 = food.getPrice.bind({ name: 'chicken'.price: 'seven dollars' }, 'Willing to beat the chicken')
getPrice1()       // Browser output: "Chicken chicken 7 bucks"
Copy the code

Implicit binding

Whether the function is called in a context object, and if so, that context object is bound to this.

var a = 'hello'

var obj = {
    a: 'world'.foo: function() {
        console.log(this.a)
    }
}

obj.foo()       // Output from browser: "world"
This is the global context, this is the obj here
Copy the code
var a = 'hello'

var obj = {
    a: 'world'.b: {a:'China'.foo: function() {
            console.log(this.a)
        }
    }
}

obj.b.foo()      // The browser output: "China"
Copy the code

The default binding

The function is called independently, directly using a function reference without any embellishments, which is also an alternative to the above binding approaches. In non-strict mode this is bound to a global object (winodW in browsers, global in Node) and in strict mode this is bound to undefined (because strict mode does not allow this to point to a global object).

var a = 'hello'

function foo() {
    var a = 'world'
    console.log(this.a)
    console.log(this)
}

foo()             // equivalent to window.foo()

// Output from browser: "hello"
// Output: Window object in browser
Copy the code
var a = 'hello'

var obj = {
    a: 'world'.foo: function() {
        console.log(this.a)
    }
}

function func(fn) The {fn()} func(obj.foo) argument passing is actually an implicit assignment, except that the obj.foo method is implicitly assigned to the fn parameter of func, whereas the previous situation was self-assigned, and the two scenarios are actually similar. This is the kind of scene that we encounter a lotsetTimeoutsetInterval, if the callback function is not the arrow function, thenthisIt points to the global object.Copy the code

Es6 in this

The arrow function’s this binding cannot be modified by call, apply, or bind, and since the arrow function does not have a constructor, it should not be called with new, or as a constructor, otherwise an error will be reported.

var a = 'hello'

var obj = {
    a: 'world'.foo: () = > {
        console.log(this.a)
    }
}

obj.foo()             // Output from browser: "hello"
Copy the code

Try their project

  • Zoe/Ruoyi-Vue gitee.com/y_project/R…

Last update, the last update time on May 26, 2021 11:19:03…

Wechat technology exchange group: CBQ2393159 group has free front-end tutorial materials, welcome to enter the group.