js基础
1. 变量提升
javascript
// 因为扫描到了let x,未先声明就调用,直接报错
var x = "parent value";
(function () {
console.log(x);
let x = "child value";
})();
// 变量提升了,var y提升到顶部,输出undefined
let y = "parent value";
(function () {
console.log(y);
var y = "child value";
})();2. 箭头函数和普通函数的this指向
javascript
let a = function () {
return {
m: function () {
console.log(this); // 普通函数
},
n: () => {
console.log(this); // 箭头函数
},
};
};
let b = {};
let c = a.call(b); // 使用 b 作为 this 调用 a,会返回return的值,所以c是这个包含m和n的对象;所以c的this指向b;所以c是这个包含m和n的对象;
c.m(); // 调用 m 方法, function是普通函数,this指向调用它的对象,所以输出c
c.n(); // 调用 n 方法,箭头函数的this指向定义它的对象,所以输出b如果把let c = a.call(b) 换成 let c=a() 呢?
- c.m()依然是取决于调用它的变量,所以还是输出c,没有变化;
- c.n()的this指向定义它的对象,也就是a的this, 所以输出window/global/undefined;
3. 事件循环
javascript
const wait = (ms) =>
new Promise((resolve) => {
setTimeout(() => {
resolve(); // 调用 resolve 使 promise 状态变为 fulfilled
console.log(0);
}, ms);
});
// 调用 wait 函数,ms 设为 0
wait().then(() => console.log(1));
// 创建一个立即 resolve 的 Promise 链
Promise.resolve()
.then(() => console.log(2))
.then(() => console.log(3));
// 同步代码
console.log(4);14, 输出题
js
async function async1() {
console.log("async1 start");
await async2();
console.log("async1 end");
}
async function async2() {
console.log("async2");
}
console.log("script start");
async1();
console.log("script end");
// start - async1 start - async2 -js
console.log(1);
setTimeout(() => { console.log(2); }, 0);
new Promise(resolve => {
console.log(6);
resolve();
}).then(() => { console.log('微任务'); });
while (true) { // 无限循环
console.log(4);
}
console.log(5); // 永远无法到达