当前位置:网站首页>JS foundation - prototype prototype chain and macro task / micro task / event mechanism
JS foundation - prototype prototype chain and macro task / micro task / event mechanism
2022-07-03 09:54:00 【Brother Xiang's words】
1、 Prototype chain
topic 1:

Familiar use new How objects are created :
(1) The implicit prototype of the new object executes the display prototype of the constructor
B._proto_ = A.protoType;
(2) Point the constructor to the new instance object .
A.call(B)

topic 2:

Output --》2, undefined
analysis :(1)a.x First, look in your constructor , Did not take the prototype to find , Here you are this.x = x. therefore a.x = 2;

topic 3:
console.log(typeof ''.prototype);
console.log(typeof ''.__proto__);
console.log(typeof ''.__proto__ === typeof ''.prototype);
Sign in — major IT Written interview preparation platform _ Cattle from
undefined、object、false
(1) character string ’‘, yes String Constructor instantiated , There is an implicit prototype on the instance _proto_, Prototype not displayed protoType, So it is undefined.
(2)''.__proto__ = String.protoType = Object type ;
(3) typeof ''.prototype namely typeof undefined by undefined
topic 4:
function Person(age){
this.age = age;
}
Person.prototype = {
constructor:Person,
getAge:function(){
console.log(this.age);
},
}
var ldh = new Person(24);
Person.prototype.age = 18;
Object.prototype.age = 20;
ldh.getAge();Objects rely on the order of the prototype chain to find when calling methods and properties , Look for yourself first , Then there is the prototype object of the constructor , Next is Object Prototype object , Once found, stop searching , Return if not found undefined. meanwhile , In prototype object this Still points to the instance object , Not prototype objects , In the subject , The instance object first calls the getAge() Method , Then the output age Property value , Because the instance object already has age attribute , At the same time, in its prototype chain , Prototype object and prototype object of prototype object are Object All the objects are age attribute , According to the above search rules , The final output result is... Of the instance object age, That is to say 24.
topic 5:
class Phone{
constructor(brand){
this.brand = brand;
}
call(){}...①
}
function playGame(){console.log(" I can play games ")};
function photo(){console.log(" I can take pictures ")};
console.log(typeof Phone);...②
var p = new Phone(' Huawei ');
console.log(p.brand);...③1、call Methods are defined in classes Phone Of prototype On the object
2、 The essence of a class is a function , actually ,ES6 Classes in can be regarded as ES5 Another way to write a constructor in , therefore ② The output result of the formula is function instead of Object.
3、p Is an instance object of a class , The object has a property brand, The attribute value is Huawei
4、 If you want to add playGame and photo Two example methods , have access to Object.assign(Phone.prototype,{playGame,photo})
topic 6:
function father() {
this.num = 935;
this.work = ['read', 'write', 'listen'];
}
function son() {}
son.prototype = new father();
let son1 = new son();
let son2 = new son();
son1.num = 117;
son1.work.pop();
console.log(son2.num);
console.log(son2.work);
// analysis
function father() {
this.num = 935;
this.work = ['read', 'write', 'listen'];
}
function son() {}
son.prototype = new father();
// son.prototype = { num:935, work:['read','write','listen'] }
let son1 = new son(); // son1 = { }
let son2 = new son(); // son2 = { }
son1.num = 117; // son1 = { num: 117 }
son1.work.pop();
//son1 I don't have work, Go to the prototype and find work, And delete work Last item in ,
// here son.prototype = { num:935, work:['read','write'] }
console.log(son2.num);// son2 I don't have num, Look in the prototype , Yes num:935
console.log(son2.work);
//son1 and son2 The prototype is the same , So now in the prototype work yes ['read', 'write']---》935、 ['read', 'write']
2、setTimeout Asynchronous task / Macro task / Micro task / Event mechanism
Promise Summary of interview questions _CUG-GZ The blog of -CSDN Blog _promise Interview questions
topic 1:

->>> 0 1 2 2
(1) The upper cycle and the lower cycle , It's all synchronous code , First execute the above , Put two asynchronous macro tasks into the event queue , Mission 1 And tasks 2(RW1,RW2: Is to use let Defined block level scope , therefore RW1 in i by 0,RW2 in i by 1)
At this time, the event queue 【RW1(i=0),RW2(i=1)】
(2) The following loop , Continue adding macro tasks to the event queue RW3、RW4, But the use of var, There is no block-level scope , When the timer is running , You need to use the outside scope i Value .
At this time, the event queue 【RW1(i=0),RW2(i=1),RW3(i=?),RW4(i=?)】
(3) The outer i by 2, Because when i=0,i=1 when , Set two tasks ,i=2 Time does not meet the conditions , But it was also implemented , Synchronization code execution completed ,i=2 Last .
(4) Start executing the event queue , Output 0,1,2,2.
Add : If the above timer events are 2000ms, That is to say 2s, Then the result is output separately , Or output together 》?
Practical verification : wait for 2s after , Output all directly 0,1,2,2.
topic 2:
for(var i=0;i<3;++i){
setTimeout(function(){
console.log(i);
},100);
}3,3,3(100ms The last output 3 individual 3)This problem involves asynchrony 、 Scope 、 Closure
settimeout It's asynchronous execution ,100ms Then add a task to the task queue , Only the main line is completely executed , Will execute the tasks in the task queue , When the main line execution is completed ,i yes 3, So when you execute the tasks in the task queue at this time ,i All is 3 了 . For printing 3 Next is :
every time for In the cycle ,settimeout It's all done once , But the function inside is not executed , It's put in the task queue , Waiting for execution ,for Circulated 3 Time , Just let it go 3 Time , When the main thread completes execution , Just enter the task queue to execute .
topic 3:
for(var i = 0; i < 5; i++){
setTimeout(function(){
console.log(i);
}, 1000 * i);
}5 5 5 5 5( Output one immediately 5, At every 1s Output one 5)1000*i: there i Actually, it is not a function to be executed by asynchronous tasks , But when it is crammed into the task queue ,i Value, that is, the time of scheduled execution, has been confirmed .
After the synchronization function is executed , Execute asynchronous tasks in the task queue , Timing of asynchronous tasks 0s,1s,2s, 3s, 4s, So what you can see is , Output one immediately 5, At every 1s Output one 5
topic 4:
let date = new Date()
setTimeout(() => {
console.log('1')
}, 2000)
setTimeout('console.log(2)',1000);
setTimeout(function() {
console.log('3')
}, 1500);
while((new Date() - date) < 3000) {}While It's a micro task , So before 3 In seconds while function ,setTimeout Although the function is inserted into the queue after their corresponding time , But because it belongs to macro task, it has not been implemented yet , until while Micro task completion , Output in order .
--》3 Output at the same time in seconds 2 3 1
topic 5:
for(let i=0;i<2;i++){
setTimeout(function(){
console.log(i)
},100);
}
for(var i=0;i<2;i++){
setTimeout(function(){
console.log(i)
},100);
}- Sign in — major IT Written interview preparation platform _ Cattle from
-》0 1 2 2
topic 6:
console.log(1);
let a = setTimeout(() => {console.log(2)}, 0);
console.log(3);
Promise.resolve(4).then(b => {
console.log(b);
clearTimeout(a);
});
console.log(5);promise Object's then() Methods are micro tasks , and setTimeout() The timer function is a macro task . In the execution of sequential processing ,js All synchronization code will be executed first , Then execute all micro tasks in the micro task queue , Finally, continue to execute the macro task . In the subject , First execute the synchronization code and output 1 3 5, Then perform Promise.resolve().then() Method , Output 4, Because in then() The timer function is deleted in the method , So no more output 2, The final output is zero 1 3 5 4
topic 7:
Promise.resolve().then(() => {
console.log('promise1');
const timer2 = setTimeout(() => {
console.log('timer2')
}, 0)
});
const timer1 = setTimeout(() => {
console.log('timer1')
Promise.resolve().then(() => {
console.log('promise2')
})
}, 0)
console.log('start');analysis :
The code executes from top to bottom :
(1) The first thing I met was Promise, It's a micro task , Put it in the task queue 【WR1】
(2) Continue to run into a macro task , Put it in the task queue 【WR1,HR1】
(3) Synchronization code , Print out start.
(4) Synchronization code execution completed , Start executing tasks in the task queue .
(5) Do the micro task first WR1, Output “promise1“, Encounter macro task 2 Join the task queue 【HR1,HR2】
(6)WR1 Micro task execution completed , Execute macro task HR1.
(7) perform HR1, First, the output “timer1”, Encounter micro task WR2, Task queue 【HR2, WR2】
(8) Macro task R1 After execution , There is also a macro task and a micro task in the task queue
(9) Do the micro task first WR2, Output promise2, When executing macro task output timer2
----> start ->promise1->timer1->promise2->timer2
topic 8:
function runAsync (x) {
const p = new Promise(r => setTimeout(() => r(x, console.log('ee--00:', x)), 1000))
return p
}
function runReject (x) {
const p = new Promise((res, rej) => setTimeout(() => rej(`Error: ${x}`, console.log('ee--11:', x)), 1000 * x))
return p
}
Promise.all([runAsync(1), runReject(4), runAsync(3), runReject(2)])
.then(res => console.log('ee--22:', res))
.catch(err => console.log('ee--33:', err))
Output results :
You can see Promise.all Carry out four promise example , Among them is reject Of , therefore promise.all The state does not change to fullfiled, That is, it will not call .then Callback function for .
(1)runAsync(1), runAsync(3), Are the two fullfied Examples of States , At the same time, the timer is 1s, therefore 1s Then output at the same time 1,3
(2)runReject(2) yes reject state ,promise.all As long as one instance state changes to reject, Then the overall state is reject, Will go .catch The callback , So the first 2s Will be output 2,Error: 2
(3)runReject(4) It's also reject state , but promise The instance state of is irreversible , from reject->reject The state remains the same , Call callback function will not be triggered , All will not be implemented .catch, The first 4s Output 4
// 1s Post output
ee--00: 1
ee--00: 3
// 2s Post output
ee--11: 2
ee--33: Error: 2
// 4s Post output
ee--11: 4
topic 9:
function runAsync(x) {
const p = new Promise(r =>
setTimeout(() => r(x, console.log(x)), 1000)
);
return p;
}
function runReject(x) {
const p = new Promise((res, rej) =>
setTimeout(() => rej(`Error: ${x}`, console.log(x)), 1000 * x)
);
return p;
}
Promise.race([runReject(0), runAsync(1), runAsync(2), runAsync(3)])
.then(res => console.log("result: ", res))
.catch(err => console.log(err));
// First, the output
0
Error: 0// 1s Output at the same time
1
2
3

result :


2、
First of all : First, distinguish between browser side and server side js Modular specification .
1) Browser side js Modular specification :AMD and CMD
2) Server side js Modular specification :CommonJS( notes : from NodeJS Realization )
second : Browser side Of js What are the modular specifications implemented by .
1)AMD By require.js Realized ( Mnemonics , Think A yes Async asynchronous , Rely on the pre - , That is, all dependencies must be placed at the top )
2)CMD By sea.js Realized ( Rely on proximity , All dependencies need to be reintroduced
//CMD Common Module Definition define(function(require, exports, module) {
var a = require('./a')
a.doSomething()
//...
var b = require('./b') // Dependence can be written nearby
b.doSomething()
// ...
})
//AMD Asynchronous Module Definition define(['./a', './b'], function(a, b) { // Dependencies must be written at the beginning
a.doSomething()
//...
b.doSomething()
//...
})边栏推荐
- 【22毕业季】我是毕业生yo~
- Getting started with JMX, MBean, mxbean, mbeanserver
- STM32 serial port usart1 routine
- 单片机学到什么程度能找到工作,这个标准不好量化
- GPIO port details, Hal library operation keys
- Electronic product design
- 干单片机这一行的时候根本没想过这么多,只想着先挣钱养活自己
- You need to use MySQL in the opening experiment. How can you forget the basic select statement? Remedy is coming~
- numpy. Reshape() and resize() functions
- byte alignment
猜你喜欢

Programming ideas are more important than anything, not more than who can use several functions, but more than the understanding of the program

Design and development of biological instruments

numpy. Reshape() and resize() functions

PRACH --- originator

Nodemcu-esp8266 development (vscode+platformio+arduino framework): Part 4 --blinker_ DHT_ WiFi (lighting technology app control + temperature and humidity data app display)

UCI and data multiplexing are transmitted on Pusch - placement of data and UCI positions (Part III)

Nr--- Pusch I: sorting out the agreement process

【男保姆式】教你打开第一个微信小程序

Code word in NR

Intelligent home design and development
随机推荐
Design and development of biological instruments
MySQL Data Definition Language DDL common commands
Project cost management__ Cost management technology__ Article 8 performance review
PIP references domestic sources
Development of fire power monitoring system
CEF下载,编译工程
【力扣刷题笔记(二)】特别技巧,模块突破,45道经典题目分类总结,在不断巩固中精进
Successful graduation [2] - student health management system function development...
[graduation successful] [1] - tour [Student Management Information System]
All processes of top ten management in project management
Nr-prach:prach format and time-frequency domain
MYSQL数据库底层基础专栏
【22毕业季】我是毕业生yo~
顺利毕业[3]-博客系统 更新中。。。
单片机职业发展:能做下去的都成牛人了,熬不动就辞职或者改行了
Leetcode daily question (931. minimum falling path sum)
NR PUCCH format0 sequence generation and detection mechanism
IDEA远程断点调试jar包项目
[Li Kou brush question notes (II)] special skills, module breakthroughs, classification and summary of 45 classic questions, and refinement in continuous consolidation
JS基础-原型原型链和宏任务/微任务/事件机制

