Juejin. Cn/post / 684490… Juejin. Cn/post / 684490…

The data type

Juejin. Cn/post / 684490…

Basic types: Boolean, Number, String, Null, Undefined: Stored in memory by value. The storage space is small and the value cannot be changed

Reference types: Object, Array, Function: Store values of variable size, can be adjusted dynamically (add/remove properties/methods), address Pointers are stored in the stack, values are stored in the heap, and new values are copied to affect each other

var obj1 = {name:"ConardLi"},obj2 = {age:18},obj3 = function(){... }, obj4 =,2,3,4,5,6,7,8,9 [1]Copy the code

Arrays, for example, the following method will change his own value: pop, push, shift, unshift, reverse, sort, splice

Check the data type mode

Juejin. Cn/post / 684490…

  1. typeof

Boolean, undefined, string, number, symbol; typeof, null; Array, Object, Object, return string

  1. Object.prototype.toString.call()
  • (Value -> is the value of the data type we are testing). Every Object that inherits Object has a toString method. However, many reference types override Object’s inherited toStrong methods, requiring call or apply to change the execution context of toString methods, which can be evaluated for all primitive types

Object. The prototype. ToString returns a string Object, class, class accurately expressed various data types, and different typeof, class represents the data type of the string of the first letter is capitalized, Unlike Typeof, which returns a lower-case string

function type(obj) { return typeof obj ! == "object" ? typeof obj : Object.prototype.toString.call(obj).slice(8, -1).toLowerCase(); }Copy the code
  1. Instanceof: Returns a Boolean value, determines the reference type, cannot determine the primitive type, and the implicit stereotype of the object on the left is equal to the display stereotype of the constructor on the right

In class archetypal inheritance,instanceof detection is inaccurate, and all Object types instanceof Object are true: [] instanceof Array; // true, [] instanceof Object; // true

  1. Object. The prototype. The hasOwnProperty () [1, 2, 3]

Returns a Boolean indicating whether the instance has the property itself, or whether it inherits from the stereotype.

  1. Construtor: Using a chain of prototypes: []. Constructor === Array

Depth copy

Juejin. Cn/post / 684490… Juejin. Cn/post / 684490… Mp.weixin.qq.com/s/g526P8gAa…

Assignment, deep/shallow copy difference

  • Assignment: Assigning an object to a new variable assigns the object’s address on the stack, not the data in the heap. That is, two objects point to the same storage space. No matter which object is changed, it is the content of the changed storage space. Therefore, the two objects are linked
  • Shallow copy: create a new object. If the property is of a primitive type, it copies the value of the primitive type. If the property is of a reference type, it copies the memory address
    • Object.assign() : Copies any number of source objects’ own enumerable attributes to the target Object and returns the target Object: let obj2 = object.assign ({}, obj1)
    • Expansion operator… Same as object.assign () : let obj2= {… obj1}
    • Var obj2 = _.clone(obj1);
    • Array.prototype.concat()
    • Array.prototype.slice() returns a new copy object
  • Deep copy: A complete copy of an object from the heap, creating a new area of the heap to store the new object, and modifying the new object does not affect the original object
    • Parse (json.stringify ()) : Converts an object into a JSON string using json.stringify, and parses the string into an object using json.parse, which opens a new stack for deep copy: But it cannot handle functions (null) and regees (empty objects)
    • Var obj2 = _. CloneDeep (obj1)
    • Handwritten recursive method: deep cloning principle: traverse the object, array until the inside are all basic data types, and then to copy, that is, deep copy

What methods do arrays have

Array methods

An array of random sequence

Array flattening

Modification: push, pop, unshift, splice, reverse, sort

Access: slice, contact, join, indexOf, includes, toString

Iteration: forEach, Map, filter, reduce, some, every

Implement Map, Reduce, and Reverce by yourself

Pure function, impure function: 9801.me/? p=2754

Do not change the original array: Join, split, slice, indexOf, lastIndexOf, includes, some, every, filter, findInex、、、、

Return new arrays: splice, unshift, reverse, sort, filter, find、、、、、、、

unshift(item1,item2,….) : adds one or more elements at the beginning, returns the new array length,

Shift (): Removes and returns the value of the first element

Push (): Finally adds one or more elements and returns the length of the new array

Pop (): Deletes last, returns an array of deleted elements

Reduce: “iterative traversal”, merges the class method, makes the front and back items in the array do some calculation, and accumulates the final value, often used for stacking, finding the maximum value of the array, array deduplication, counting the number of occurrences of each value, and summing, can replace forEach

Reduce (callback,initiaValue) passes in two variables, the callback function (callback) and the initial value (initiaValue).

Suppose the function has four incoming arguments, prev and next, index and array. Prev and next are the ones you need to know.

When no initial value is passed in, prev starts from the first element in the array, and the next array is the second element. But when the initial value (initiaValue) is passed in, the first prev will be initivalValue and next will be the first element in the array

Prototype and prototype chain

Prototype/Prototype chain

You can know the concept of the prototype chain, know that the source is null, the next layer is Object.prototype

Js itself is a prototype-based inheritance language, es6 before the implementation of inheritance through prototypes, ES6 after the implementation of class inheritance

Mode of inheritance: the difference between a class and how understanding of nature of the class prototype: constructor and superhttps: / / juejin. Cn/post / 6844903638674980872

  • An illustration of prototypes and prototype chains: Prototype and __proto__
  • Execution rules for properties and methods

Declare classes: classes are actually functions

class Peoplet{constructor(name){this.name = name}}

Const xia = new Peoplet(‘test’,100)

Inheritance: A subclass inherits extends from its parent

Class Student extends People{constructor(){super(name)}}Copy the code

And instanceof: implicit and display archetypes

Every class, every function has a prototype display

Each instance, each reference type has an implicit prototype __proto__

The instance’s __proto__ points to the class’s prototype

Prototype-based execution rules: When retrieving an Object property or method that doesn’t have the property itself, look for object.prototype. __proto__ in its implicit prototype __proto__(the prototype of its constructor) and always point to null

Instanceof: Returns a Boolean value

HasOwnProperty: Checks if it is its own property and method

Scope and closure

scope

Global scope, function scope, block-level scope

Scope is the legal scope of a variable:

Free variable: a variable is not defined in the current scope, but is used, and is searched for in the upper scope layer by layer until it is found (even if the variable is defined in the outer layer, only the variable found in the first layer is used). If it is not found in the global scope, an error is reported

this

This points to the

Description: For a function, the object that points to the last called function is an internal object automatically generated when the function is running, and can only be used within the function. For the global, this refers to the window

This always refers to the object that last called it. There are four methods that a function can call:

  1. Normal function call –>window: fn()
var name = "windowsName"; function fn() { var name = 'Cherry'; innerFunction(); Function innerFunction() {console.log(this.name); // Call as a function (it is called as a function, not mounted on any object). // windowsName }} fn()Copy the code
  1. Called as an object method –> Instance object (this object) : a.fein ();
  2. Called as a timer –>window
  3. Call the function (new)–> instance object using the constructor
  4. Call functions (call, apply, bind) as function methods –>

window.a.fn(); / The last call to function a is fn()

var name = "windowsName"; var a = { name : null, // name: "Cherry", fn : function () { console.log(this.name); // windowsName } } var f = a.fn; // The fn method of a is assigned to f, but f() is not called; // This always refers to the object that last called it, so print windowsName tips:Copy the code

The role of the origin and backup of this: www.ruanyifeng.com/blog/2018/0…

Var that=this; var that=this; var that=this; var that=this; var that=this; var that=this

Change the direction of this

This points to the specified context

  1. Arrow function

The arrow function’s this always points to this when the function is defined, not when it is executed

Arrow functions do not have this binding, so you must determine its value by searching the scope chain. If the arrow function is contained by a non-arrow function, this is bound to the nearest non-arrow function’s this. Otherwise, this is undefined.”

  1. Back up this: use _this = this inside the function

Store the object on which this function is called in the _this variable first, and then use the _this variable throughout the function so that _this does not change

var name = "windowsName"; var a = { name : "Cherry", func1: function () { console.log(this.name) }, func2: function () { var _this = this; setTimeout( function() { _this.func1() },100); }}; A.unc2 () // Cherry tips: In func2, var _this = this; , where this is the object A that calls func2. In order to prevent setTimeout in func2 from being called by window, this in setTimeout is window. Assign this(pointing to variable A) to a variable _this, thus using _this in func2 refers to object ACopy the code
  1. Use apply, call, and bind
  2. New instantiates an object

This is based on priority: New binding > Show Binding > Implicit binding > Default binding

Process of new:

  1. Create an empty object obj;
  2. Points the implicit stereotype of the newly created empty object to the display stereotype of its constructor.
  3. Use call to redirect this
  4. If no value is returned or a non-object value is returned, obj is returned as the new object; If the return value is a new object, return that object directly
var a = new myFunction("Li","Cherry"); new myFunction{ var obj = {}; obj.__proto__ = myFunction.prototype; var result = myFunction.call(obj,"Li","Cherry"); return typeof result === 'obj'? result : obj; } // During new, use call to change the direction of thisCopy the code

New /call/apply/bind principle: juejin.cn/post/684490…

Call accepts a list of arguments, whereas Apply accepts an array of arguments

var a ={ name : "Cherry", fn : function (a,b) { console.log( a + b) } } var b = a.fn; B.a pply (a, [1, 2]) / / / / or: biggest all (a, 1, 2) / / 3 / / b.b ind (a, 1, 2) (a) / / 3 bind is to create a new function, we have to manually to callCopy the code

closure

Garbage collection and memory leaks

Closures are a representation of scopes and chains of scopes

Two common ways :& free variable lookup rules

Normally, functions are called where they are defined, but closures are defined and called in different ways. The special case of scoped applications can manifest itself in two ways: functions are passed as arguments, and functions are returned as return values

As a parameter:  function create() { const a = 100 return function () {console.log(a)}} const fn = Const a = 200; const a = 200; const a = 200; const a = 200; Fn () / / 100,Copy the code
As a return value:  function print(fn) {let a = 200 fn()} let a = 100 function fn() {console.log(a)} print(fn)//100 function print(fn){let a = 200 fn()} let a = 100 function fn(){console.log(a)} print(fn)//100Copy the code

All lookups for free variables are in the function definition, in the parent scope, not in the execution!! Application in real development: Hiding data: Using closures to hide some data from the outside world

Juejin. Cn/post / 684490…

Application scenarios

Anti-shake and throttling

  1. Throttle: No matter how many callbacks you trigger in a given period of time, I will only recognize the first one and give a response when the timer ends.
  2. Debounce: No matter how many times you trigger a callback in a given period of time, I only think it’s the last one

Juejin. Cn/post / 684490… Juejin. Cn/post / 684490…

Both are designed to solve performance problems caused by firing a large number of functions in a short period of time

Principle: The event response function is executed only once within n seconds. If triggered again within n seconds, the timer is cleared and a new timer is created to recalculate the time

Thorttle: Executes only once in n seconds. If it continues, executes only once at intervals

What is a closure? What are the characteristics and negative effects?

Scope and free variables (lookups for free variables should be where the function is defined, not executed)

Application scenario: Passed as a parameter and returned as a return value

Negative: Variables are stored in memory and cannot be freed. Closures are not meant to leak memory, but are saved because they will not be used again

Learn from reading

Design Pattern: juejin.cn/post/684490… Juejin. Cn/post / 684490… Mp.weixin.qq.com/s/X40KEH37c… Juejin. Cn/post / 684490… Call/apply/bind: juejin. Cn/post / 684490… Prototype/Prototype chain: juejin.cn/post/684490…