this判断+异步任务执行顺序-闭包/Promise复习

1.闭包

var result = [];
var a = 3;
let total = 0;

function foo(a) {
    
    
  var i = 0;
  for (; i < 3; i++) {
    
    
    console.log('i', i);	//都是同步, 所以会输出0,1,2
    result[i] = function() {
    
     //一直到赋值语句都是同步的,所以result[0,1,2]都被赋值成功,但执行时内部i是闭包
      total += i * a;
      console.log(total);
    }
  }
}
foo(1); //赋值result[0,1,2], 结束时i=3, 因为i的引用在作用域链中, i不会被回收, 一直为3; a也成了闭包, 相当于执行foo时, var a=1, 此引用也不会被回收; total作为全局变量, 跟用let和var无关;
result[0](); //执行时, a=1, i=3; total = 3;
result[1](); //执行时, a=1, i=3; 未做更改, total=3+3=6;
result[2](); //9
  1. Promise构造函数

参考: https://www.cnblogs.com/lvdabao/p/es6-promise-1.html

new Promise(function(resolve, reject){}), 一个Promise实例接收一个函数参数, 这个函数参数又接收两个函数名作为回调, 确定Promise实例的状态;

Promise的这个函数传参, 在new Promise时会被立即执行; 而resolve()和reject()会写在该参数函数内, 随着该参数函数一起执行;

Promise的.then接收一个函数参数时,会拿到我们在runAsync中调用resolve时传的的参数。then里面的函数就跟我们平时的回调函数一个意思,能够在new Promise(func(){})这个异步任务执行完成之后被执行。
Promise的.then接收两个个函数参数时, 分别会拿到resolve(data1)和reject(data2)执行时传进去的data1和data2;

function runAsync(){
    
    
    var p = new Promise(function(resolve, reject){
    
    
        //做一些异步操作
        setTimeout(function(){
    
    
            console.log('执行完成');
            resolve('随便什么数据');
        }, 2000);
    });
    return p;            
}
runAsync().then(function(data){
    
    
    console.log(data);
    //'随便什么数据'
    //......
});

请问下述代码输出:

    async function async1() {
    
    
      console.log('async1 start');
      await async2();
      console.log('async1 end');
    }
    async function async2() {
    
    
      console.log('async2 start');
      return new Promise((resolve, reject) => {
    
    
        resolve();
        console.log('async2 promise');
      })
    }
    console.log('script start'); //1
    setTimeout(function() {
    
    
      console.log('setTimeout'); //last
    }, 0);
    async1(); //这一句注释呢?
    new Promise(function(resolve) {
    
    
      console.log('promise1'); //2
      resolve(); //
    }).then(function(resolve) {
    
    
      console.log('promise2');
    }).then(function() {
    
    
      console.log('promise3');
    });
    console.log('script end');

3.this判断

    var val = 10;
    let a = function() {
    
    
      console.log(this.val);
      console.log('a的this', this);
    }
    a.prototype.val = 9;
    val = 3;
    a();
    let b = new a; //b作为a的实例, 此处执行时this指向a本身
    // let b = new a(); //带不带括号效果一样

    console.log(b.val)

Supongo que te gusta

Origin blog.csdn.net/Fky_mie/article/details/120394692
Recomendado
Clasificación