技巧-奇技淫巧
1. this
1.1 第一题: this的指向
var length = 4;
function callback() {
console.log(this.length); // 输出什么
}
const object = {
length: 5,
method() {
arguments[0]();
}
};
object.method(callback, 1, 2);
输出结果: '3'
分析: 这里的this实际上指向的是method函数本身, 而函数的属性length实际上会输出当前函数的调用参数的个数.
1.2 第二题: this的指向2
let length = 10
function fn() {
console.log(this.length)
}
let obj = {
length: 5,
method(fn) {
fn()
}
}
obj.method(fn, 1)
输出: 当前页面中iframe/frame的数量
分析: 这里的fn是直接调用的, 所以this指向window, 而window上的length只的是当前页面中iframe/frame的输血量
2. 异步
2.1 第一题: Promise.resolve的异步顺序
请问输出的顺序
Promise.resolve().then(() => {
console.log(1);
return Promise.resolve(3);
}).then((res) => {
console.log(res)
})
Promise.resolve()
.then(() => {
console.log(2);
})
.then(() => {
console.log(4);
})
.then(() => {
console.log(5);
})
.then(() => {
console.log(6);
})
.then(() => {
console.log(7);
});
输出:
1 2 4 5 3 6 7
分析:
2.2 第二题: await的细节
let a = 0
let b = async () => {
a = a + await 0
console.log('2', a)
}
b()
a++
console.log('1', a)