Table of contents
person.prototype.isPrototypeOf(stu)
Object.getPrototypeOf(Object) replaces the deprecated Object._ _ proto _ _
Object.create(instance) creates a new object using an existing object as a prototype
Function decorator: add additional logic before or after a function is executed
Pre-ES6: Constructors and Prototype Chains
2. Class method: constructor.prototype.fun=function(){}
1. Constructor: parent class constructor.call(this,x)
2. Prototype chain: Dog.prototype = Object.create(Animal.prototype)
3. Correct the constructor on prototype: Dog.prototype.constructor = Dog
There is no constructor (it will be created by default)
Word segmentation/lexical analysis: decomposition (var a=2=> var,a,=,2)
Code generation: convert AST into executable code
Global execution context: this points to the window global object
Function execution context: Each call creates a new execution context
A scope is created when a function is created, and a pointer is placed when it is called.
scope chain = scope linked list
Not found: prototype chain undefined, scope chain ReferenceError
Global environment (normal function/anonymous function): window/undefined strict mode
the object calling the function
Memory leak: memory waste -> slowness -> crash
Modularity specification: A module = a set of methods that implement a specific function.
Several functions: pollution of global variables, no connection between modules.
WeakSet: Weak reference (will be recycled when not referenced) object
WeakMap: key (weak reference object)/value pair
Object: Key: String, Symbol, JSON serialization JSON.stringify() and parsing JSON.parse()
Destructuring assignment of variables: getting values from arrays/objects
Array/Object: spread operator (shallow copy)
Inherit this from the previous scope chain
Do not bind arguments, use rest parameters
ES7’s async/await function replaces ES6’s Generator function
String method: ${ }, single backquote
ES6 pre-scope: global variables and local variables within functions.
Block-level scope {}: if(){}, for(){}, etc.
var: repeated declaration, variable promotion
let, const: access in block scope, no repeated declarations, variable promotion
const: must be initialized (SyntaxError), stack value/memory address unchanged (TypeError)
Syntactic sugar for defining classes (class)
API: fetch is based on promise
Number (any type): If string contains non-number, NaN will be returned.
parseInt(string[,radix]): The base radix is an integer between 2-36
parseFloat(string): Parses a parameter and returns a floating point number
Implicit conversion: +str-, addition with boolean
Except null/undefined.toString()
Implicit conversion: addition with str
Boolean(): 0, '' (empty string), null, undefined, NaN will be converted to false, others are true
typeof: determine basic data type
typeof null=Object type labels are all 000
Instance instanceof constructor: determine prototype chain, and isPrototypeOf
Constructor.prototype.isPrototypeOf(instance): Determine the prototype chain
(data).constructor === Data type: does not include inherited types
Display: toString, valueOf except null, undefined
valueOf: this value is converted into an object. Except for Date, the data itself is returned.
toString: Override the type conversion of the object. console.log
Global property NaN: a non-numeric value that is not equal to any other value (including itself)
Object.is(val0, val1)和===:NaN、±0
Loose equality == (can automatically convert types) and strict equality ===
The contents of memory cells are compared
Object transfer is a reference address: judging objects to be equal requires deep comparison.
DOM event flow: Capture->Bubbling
for of: val, Object.keys(obj) own property
for in: idx, including inherited enumerable properties
Public enumerable properties of traversable objects (except symbol properties)
obj.hasOwnProperty(prop) avoids traversing properties on the prototype chain
forEach(value[, index, arr]): does not change the original array and returns undefined
Unable to break (break (Illegal break statement) and return (invalid))
map(value[, index, arr]): returns a new array
The execution speed is better than forEach (the bottom layer is optimized)
Higher-order functions: params / return func
Function currying: return func
Lazy evaluation: will only be executed if all arguments have been passed
Code Reuse: Reuse code that handles similar logic in different situations
Change the array: in and out *4, splice, sort, reverse, fill
prototype chain
引用类型:
__proto__(隐式原型)
Properties, property values are object
函数:
prototype(原型)
properties, property values are objects
related methods
person.prototype.isPrototypeOf(stu)
Object.getPrototypeOf( Object ) replaces the deprecated Object._ _ proto _ _
Object.create(instance) creates a new object using an existing object as a prototype
application
new
var a=1;
function fn1(){
var a=2;
console.log(this.a+a);
}
//f1并没有被作为对象的方法调用, this 指向全局对象,在浏览器中是 window
f1();//3
function fn2(){
var a=10;
fn1();
}
//在 fn2 函数内部调用 fn1 函数,但是 fn1 函数内部的 this 仍然指向全局对象 window,因为 fn1 并没有被作为方法调用。
fn2();//3
var fn3=function(){
this.a=3;
}
fn3.prototype={
a:4
}
var fn33=new fn3();
fn1.call(fn33)
//5
Function decorator: add additional logic before or after a function is executed
Function.prototype.before=function(beforefn){
return ()=>{
beforefn.apply(this,arguments)
return this.apply(this,arguments)
}
}
Function.prototype.after=function(afterfn){
return ()=>{
var res=this.apply(this,arguments)
afterfn.apply(this,arguments)
return res;
}
}
var func=function(){
console.log(1)
}.before(function(){
console.log(2)
}).after(function(){
console.log(3)
})
func()//213
class class
Pre-ES6: Constructors and Prototype Chains
1. Constructor: this.x=x
2. Class method: constructor.prototype.fun=function(){}
inherit
1. Constructor: parent class constructor.call(this,x)
2. Prototype chain: Dog.prototype = Object.create(Animal.prototype)
3. Correct the constructor on prototype: Dog.prototype.constructor = Dog
// 使用构造函数和原型链定义"类"
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
console.log(this.name + ' makes a sound.');
};
// 创建类的实例
const dog = new Animal('Dog');
dog.speak(); // 输出: "Dog makes a sound."
// 继承一个"类"
function Dog(name, breed) {
Animal.call(this, name);
this.breed = breed;
}
//Object.create() 静态方法以一个现有对象作为原型,创建一个新对象
Dog.prototype = Object.create(Animal.prototype);
//修正构造函数
Dog.prototype.constructor = Dog;
Dog.prototype.speak = function() {
console.log(this.name + ' barks loudly.');
};
const myDog = new Dog('Buddy', 'Golden Retriever');
myDog.speak(); // 输出: "Buddy barks loudly."
ES6:class
There is no constructor (it will be created by default)
super must implement
compile
Word segmentation/lexical analysis: decomposition (var a=2=> var,a,=,2)
Parsing/syntax analysis: Lexical array => "Abstract Syntax Tree" (a->2) (Abstract Syntax Tree, AST) of the program syntax structure
Code generation: convert AST into executable code
Execution context /scope: The execution environment (variable + function) is stored in the variable object
Global execution context: this points to the window global object
Function execution context: Each call creates a new execution context
A scope is created when a function is created, and a pointer is placed when it is called.
()=>{}Application: Sharing the execution context of external functions (this, performance optimization)
//函数内部找不到就会去外层作用域
function foo() {
console.log(a);
}
function bar() {
let a="bar"
foo();
}
let a="window"
bar(); //window
scope chain = scope linked list
Could not find: prototype chain undefined, scope chain ReferenceError
this
Global environment (ordinary function/anonymous function): window/ undefined strict mode
the object calling the function
JS pre-parsing/ compilation (variable promotion): var (only declaration, no assignment), function variable creation scope
//虽然按顺序创建作用域,不会报错a为声明
function foo() {
console.log(a);
}
function bar() {
var a="bar"
foo();
}
bar(); //undefined
var a="window"
Closure: The function returns a function , and the child function calls a variable in the parent scope
Because the js scope life cycle depends on whether the internal scripts are all executed before they are destroyed and will not be brought to the parent scope ;
Because it is referenced in the subordinate scope and has not been released . As a result, the variables in the upper-level scope will not be released until the lower-level scope is executed or when the closure (subfunction) is no longer referenced .
function createCounter() {
let counter = 0
const myFunction = function() {
counter = counter + 1
return counter
}
return myFunction
}
const increment = createCounter()
const c1 = increment()
const c2 = increment()
const c3 = increment()
console.log('example increment', c1, c2, c3)//1 2 3
- Closures will cause all variables in the function to be stored in memory, which consumes a lot of memory, so closures cannot be abused.
- Misuse of closures is prone to memory leaks .
- Usage scenarios: anti-shake, throttling , function within function to avoid global pollution
Memory leak: memory waste -> slowness -> crash
No longer used/null references are not removed: closures/DOM are removed, child node references are not removed
: Automatic periodic , unwanted references set to null
(GC)Garbage Collection
The browser 's js has an automatic garbage collection mechanism. The garbage collection mechanism is also an automatic memory management mechanism. The garbage collector will regularly find inaccessible values and then release the memory, so just set unnecessary objects to null .
Modularity specification : A module = a set of methods that implement a specific function .
-
Several functions: pollution of global variables , no connection between modules .
// 模块A
var ModuleA = {
func1: function() {
// ...
},
func2: function() {
// ...
}
};
// 模块B
var ModuleB = {
func3: function() {
// ...
}
};
- Objects were proposed later, which are implemented by treating functions as an object method , but this method will expose all module members, and external code can modify the values of internal properties .
- The most commonly used method now is to write functions that execute immediately , using closures to establish the private scope of the module without polluting the global scope .
//IIFE(立即调用函数表达式)
//创建一个私有作用域,避免变量之间的冲突。然后,通过返回一个对象或函数来暴露模块的公共部分
// 模块A
var ModuleA = (function() {
var privateVar = "private";
function privateFunc() {
// ...
}
return {
publicVar: "public",
publicFunc: function() {
// ...
}
};
})();
- ES6: Use import and export forms to import and export modules.
ES6 new
type of data:
Basic Symbol, Bigint (ES10)
let bnum=1684424684321231561n //方式1:数组后加n
bunm=BigInt("1684424684321231561")//方式2:调用BigInt
Reference/(Object) Object Set, Map (key (string, symbol)/value pair), Promise (solve callback hell), Proxy
WeakSet:
Weak reference (will be recycled when not referenced) object
WeakMap
: key (weak reference object )/value pair
Map:
Any value (function, object, primitive type) can be used as key/value, size, iterable, pruning optimization,
Object
:Keys: String , Symbol, JSON serialization JSON.stringify() and parsing JSON.parse()
operator
Destructuring assignment of variables : getting values from arrays/objects
// 提取部分数组元素,其余元素放在剩余数组中
const numbers = [1, 2, 3, 4, 5];
const [first, second, ...rest] = numbers;
console.log(first); // 输出: 1
console.log(second); // 输出: 2
console.log(rest); // 输出: [3, 4, 5]
// 从对象中提取属性并赋值给变量
const person = { firstName: 'John', lastName: 'Doe' };
const { firstName, lastName } = person;
console.log(firstName); // 输出: John
console.log(lastName); // 输出: Doe
// 提取属性并赋值给变量,并指定默认值
const { age = 30, occupation = 'Engineer' } = person;
console.log(age); // 输出: 30 (因为age属性不存在)
console.log(occupation); // 输出: Engineer (因为occupation属性不存在)
const nestedObject = {
outer: {
inner: {
deep: 'Hello, nested!'
}
}
};
const { outer: { inner: { deep } } } = nestedObject;
console.log(deep); // 输出: Hello, nested!
Array/Object : spread operator (shallow copy)
function
Arrow functions: concise
Inherit this from the previous scope chain
Do not bind arguments , use rest parameters
Because there is no function declaration, there is no prototype prototype, so it cannot be used as a constructor.
rest parameter: ...real array
function sum(...numbers) {
let total = 0;
for (let number of numbers) {
total += number;
}
return total;
}
console.log(sum(1, 2, 3)); // 输出 6
ES7’s async/await function replaces ES6’s Generator function
String method : ${ }, single backquote
Block-level scope: let,const
ES6 front scope: global variables and local variables within functions .
Block-level scope {}: if(){}, for(){}, etc.
var: repeated declaration, variable promotion
let, const: access in block scope , no repeated declarations, variable promotion
const: must be initialized ( SyntaxError ) , stack value/memory address unchanged (TypeError)
Syntactic sugar for defining classes (class)
Modular import/export
API: fetch is based on promise
type conversion
Number
explicit type conversion
Number (any type): If string contains non-number, NaN will be returned.
parseInt(string[,radix]): The base radix is an integer between 2-36
parseFloat(string): Parses a parameter and returns a floating point number
Implicit conversion: +str-, addition with boolean
str = '123'
-
str - 1 //122
-
+str+1 // 124
-
str+1 // '1231'
string
explicit type conversion
Except null/undefined.toString()
String (any type)
Implicit conversion: addition with str
Boolean
explicit type conversion
Boolean(): 0, '' (empty string), null, undefined, NaN will be converted to false, others are true
Implicit conversion: !!
Determine data type
operator
typeof: determine basic data type
typeof null=Object type labels are all 000
实例
instanceof 构造函数
: determine the prototype chain, andisPrototypeOf
Object.prototype.isPrototypeOf({})// true
{} instanceof Object// true
method
构造函数.
prototype. isPrototypeOf(实例)
: Determine the prototype chain
( data ).constructor === Data type : does not contain inherited types
Display: toString, valueOf except null, undefined
valueOf: Convert this
value to object . Except for Date , the data itself is returned.
console.log
toString: Override the type conversion of the object . console.log
equal
Global property NaN
: a non-numeric value that is not equal to any other value (including itself)
Object.is(val0, val1)和===:NaN、±0
Object.is()
The "SameValueZero" comparison algorithm is used, which does not NaN
treat s specially, but compares according to strict value equality rules
console.log(NaN===NaN);
// Expected output: false
console.log(NaN==NaN);
// Expected output: false
console.log(Object.is(NaN, NaN));
// Expected output: true
console.log(Object.is(-0, +0));
// Expected output: false
console.log(Object.is(null, undefined));
// Expected output: false
When signed 0 and NaN
value. ===
The operator (and ==
operator) treats numeric sums -0
as +0
equal, but NaNs as unequal to each other.
Loose equality == (can automatically convert types) and strict equality ===
The contents of memory cells are compared
Object transfer is a reference address: judging objects to be equal requires deep comparison.
const obj = {};
console.log(Object.is(obj, {}));
// Expected output: false
NaN==/===In //false
null===undefined //false
null==undefined //true
set judgment === equal
//Set用===判断是否相等
const set= new Set();
const obj1={ x: 10, y: 20 },obj2={ x: 10, y: 20 }
set.add(obj1).add(obj2);
console.log(obj1===obj2);//false
console.log(set.size);// 2
set.add(obj1);
console.log(obj1===obj1);//true
console.log(set.size);//2
DOM event flow: Capture->Bubbling
- Event capture : From the outside to the inside, starting from the root node where the event occurs , searching downwards step by step until you reach the target element.
- Event bubbling : from the inside out, triggered from the specific target element, and passed upward step by step until the root node .
element.addEventListener(event, function[, useCapture]);
//useCapture 默认为false,即冒泡阶段调用事件处理函数,
//为ture时,在事件捕获阶段调用处理函数
iterate(str, num, set, map)
for of: val, Object.keys(obj) own property
for in: idx, including inherited enumerable properties
Public enumerable properties of traversable objects (except symbol properties)
obj.hasOwnProperty(prop) avoids traversing properties on the prototype chain
forEach(value[, index, arr]): does not change the original array and returns undefined
Unable to break ( break (Illegal break statement) and return (invalid) )
map(value[, index, arr]): return new array
The execution speed is better than forEach (the bottom layer is optimized)
Higher-order functions : params / return func
Function currying : return func
Parameter reuse: A multi-parameter function can be converted into a series of functions that only accept one parameter, which allows the parameters to be reused in different environments.
Partial application: You can partially apply a function, passing only some parameters and returning a new function that accepts the remaining parameters.
Function composition: Currying can make it easier to perform function composition, combining multiple small functions into larger functions, improving the readability and maintainability of the code.
Delayed evaluation: only executed when all arguments have been passed
Code reuse: Reuse code that handles similar logic in different situations
Change the array : in and out *4, splice, sort, reverse, fill