1考察变量提升,执行顺序,this,继承
function Foo() {
getName = function() {
console.log(1)
}
return this
}
Foo.getName = function() {
console.log(2);
}
Foo.prototype.getName = function() {
console.log(3);
}
var getName = function() {
console.log(4)
}
function getName() {
console.log(5)
}
Foo.getName();
getName();
Foo().getName();
getName();
new Foo.getName();
new Foo().getName();
new new Foo().getName();
2函数中的this 指向他的调用者
var Obj = {
foo: 'bar',
func:function(){
var self = this
console.log(this.foo);
console.log(self.foo);
(function(){
console.log(this.foo)
console.log(self.foo)
})()
}
}
Obj.func()
class Foo {
name = "Foo";
a() {
console.log(this.name);
}
b = function() {
console.log(this.name);
}
c = ()=> {
console.log(this.name);
}
}
let f = new Foo();
let d = {name: "bar", a: f.a, b: f.b, c: f.c};
f.a();
f.b();
f.c();
d.a();
d.b();
d.c();
3闭包
function fun(n,o) {
console.log(o)
return {
fun:function(m){
return fun(m,n);
}
};
}
var a = fun(0); a.fun(1); a.fun(2); a.fun(3);
var b = fun(0).fun(1).fun(2).fun(3);
var c = fun(0).fun(1); c.fun(2); c.fun(3);
promise await settimeout
console.log('script start')
async function async1() {
await async2()
console.log('async1 end')
}
async function async2() {
console.log('async2 end')
}
async1()
setTimeout(function() {
console.log('setTimeout')
}, 0)
new Promise(resolve => {
console.log('Promise')
resolve()
})
.then(function() {
console.log('promise1')
})
.then(function() {
console.log('promise2')
})
console.log('script end')
边看输出结果,边做解释吧:
1. 正常输出`script start`
2. 执行`async1`函数,此函数中又调用了`async2`函数,输出`async2 end`。回到`async1`函数,**遇到了`await`,让出线程**。
3. 遇到`setTimeout`,扔到**下一轮宏任务队列**
4. 遇到`Promise`对象,立即执行其函数,输出`Promise`。其后的`resolve`,被扔到了微任务队列
5. 正常输出`script end`
6. 此时,此次`Event Loop`宏任务都执行完了。来看下第二步被扔进来的微任务,因为`async2`函数是`async`关键词修饰,因此,将`await async2`后的代码扔到微任务队列中
7. 执行第4步被扔到微任务队列的任务,输出`promise1`和`promise2`
8. 执行第6步被扔到微任务队列的任务,输出`async1 end`
9. 第一轮EventLoop完成,执行第二轮EventLoop。执行`setTimeout`中的回调函数,输出`setTimeout`。
参考原文链接